Skip to content

Add RISC-V approximate fast path to getApproximateTime - #189000

Closed
CodersAcademy006 wants to merge 1 commit into
pytorch:mainfrom
CodersAcademy006:riscv/approximate-clock-rdtime
Closed

CodersAcademy006 wants to merge 1 commit into
pytorch:mainfrom
CodersAcademy006:riscv/approximate-clock-rdtime

Conversation

@CodersAcademy006

Copy link
Copy Markdown
Contributor

Summary

getApproximateTime() returns a cheap monotonic counter that the profiler calibrates against wall-clock time, avoiding a clock_gettime syscall on every timestamp. It uses __rdtsc on x86 and cntvct_el0 on aarch64, but had no RISC-V branch — so on RISC-V every timestamp fell back to the getTime() syscall path, the slow path this mechanism exists to avoid.

This adds a RISC-V (rv64) fast path that reads the time CSR via rdtime, mirroring the aarch64 cntvct_el0 path from #178639.

Details

rdtime is a constant-frequency counter and is user-readable on Linux — the same assumption the aarch64 path already makes for cntvct_el0. The branch is gated on __riscv_xlen == 64 because on RV32 rdtime returns only the low 32 bits, so RV32 correctly keeps the getTime() fallback.

Alternative considered: rdcycle. It counts core cycles, which vary with frequency scaling and are commonly privileged (trap) in user mode, so it is unsuitable for a wall-time approximation; rdtime is the right counter.

Test plan

# riscv64 emits the rdtime fast path:
clang --target=riscv64-unknown-elf -march=rv64gc -ffreestanding -O2 -c harness.c
llvm-objdump -d harness.o        # getApproximateTime: c0102573  rdtime a0

# rv32 correctly keeps the syscall fallback (no rdtime, calls getTime):
clang --target=riscv32-unknown-elf -march=rv32gc -ffreestanding -O2 -c harness.c
llvm-objdump -dr harness.o       # no rdtime; R_RISCV_CALL_PLT getTime

# existing aarch64 path still compiles and runs (verified natively):
clang harness.c -o t && ./t      # rc=0

Part of the RISC-V enablement effort #180975 (Phase 1.3).

cc @scotts (author of the aarch64 fast path in #178639, which this mirrors) @ryanzhang22

getApproximateTime() returns a cheap monotonic counter that the profiler
calibrates against wall-clock time, avoiding a clock_gettime syscall per
timestamp. It uses __rdtsc on x86 and cntvct_el0 on aarch64, but had no
RISC-V branch, so on RISC-V every timestamp fell back to the getTime()
syscall path -- the slow path this mechanism exists to avoid.

Add a RISC-V (rv64) fast path that reads the `time` CSR via rdtime,
mirroring the aarch64 cntvct_el0 path added in pytorch#178639. rdtime is a
constant-frequency counter and is user-readable on Linux, the same
assumption the aarch64 path already makes for cntvct_el0. The branch is
gated on __riscv_xlen == 64 because on RV32 rdtime returns only the low
32 bits, so RV32 correctly keeps the getTime() fallback.

Alternative considered: rdcycle. It counts core cycles, which vary with
frequency scaling and are commonly privileged (trap) in user mode, so it
is unsuitable for a wall-time approximation; rdtime is the right counter.

Part of the RISC-V enablement effort (pytorch#180975, Phase 1.3).

Test Plan:

    # riscv64 emits the rdtime fast path:
    clang --target=riscv64-unknown-elf -march=rv64gc -ffreestanding -O2 \
      -c harness.c && llvm-objdump -d harness.o
    #   getApproximateTime: c0102573  rdtime a0

    # rv32 correctly keeps the syscall fallback (no rdtime, calls getTime):
    clang --target=riscv32-unknown-elf -march=rv32gc -ffreestanding -O2 \
      -c harness.c && llvm-objdump -dr harness.o
    #   no rdtime; R_RISCV_CALL_PLT getTime

    # existing aarch64 path still compiles and runs (verified natively):
    clang harness.c -o t && ./t    # rc=0
@pytorch-bot

pytorch-bot Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/189000

Note: Links to docs will display an error until the docs builds have been completed.

❌ 1 New Failure, 1 Unclassified Failure

As of commit 30f354b with merge base d12b917 (image):

NEW FAILURE - The following job has failed:

UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:

  • riscv64 / pytorch-linux-noble-riscv64-py3_12-gcc14-cross-build / build-osdc (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    ModuleNotFoundError: No module named 'setuptools.command.bdist_wheel'

    AI verdict: AI verdict: not related

    The commit only adds a RISC-V #ifdef branch in a C++ header (c10/util/ApproximateClock.h). The failure is a Python setuptools environment error ("No module named 'setuptools.command.bdist_wheel'") in the riscv64 build job, which has been failing consistently in every run going back to May 2026 with various build environment issues.

    Full reasoning on HUD →

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@CodersAcademy006

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "module: risc-v" "topic: not user facing" "ciflow/riscv64"

@pytorch-bot

pytorch-bot Bot commented Jul 6, 2026

Copy link
Copy Markdown

The ciflow label(s) ciflow/riscv64 will be added, but CI won't be triggered until the workflows are approved (scroll to the bottom of this page).

Please ping one of the reviewers if you do not have access to approve and run workflows.

@pytorch-bot pytorch-bot Bot added ciflow/riscv64 module: risc-v All issues related to RISC-V architecture topic: not user facing topic category labels Jul 6, 2026
@pytorch-bot

pytorch-bot Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@ezyang

ezyang commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

@claude is this correct for risc-v. Is there risk for non risc-v archs

@ezyang ezyang added the mergedog mergedog is watching this PR label Jul 6, 2026
@claude

claude Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Claude finished @ezyang's task in 1m 31s —— View job


Answer: Correct for RISC-V, and no risk to non-RISC-V archs

I reviewed c10/util/ApproximateClock.h. Short version: the RISC-V path is correct, and the change is inert on every non-RISC-V target.

Is it correct for RISC-V? Yes.

  • rdtime is the right instruction. rdtime reads the time CSR (csrr rd, time, CSR 0xC01), a fixed-frequency real-time counter. That matches the semantics getApproximateTime() wants — a cheap monotonic tick calibrated against wall-clock during post-processing. As the PR notes, rdcycle would be wrong here (frequency-varying and typically privileged in U-mode), so rdtime is the correct choice, directly analogous to cntvct_el0 on aarch64.
  • The __riscv_xlen == 64 gate is correct. On RV64, rdtime delivers the full 64-bit counter in one register, matching the uint64_t return type. On RV32, rdtime yields only the low 32 bits (the high half needs a separate rdtimeh), so gating on rv64 and letting RV32 fall through to getTime() (line 112) is the right call — no truncated/wrapping counter on RV32.
  • Type contract holds. getRiscvApproximateTime() returns uint64_t, which satisfies the static_assert at lines 117-120 (int64_t || uint64_t).

One caveat worth being aware of (not a bug, and it also applies to the aarch64 path): user-mode rdtime relies on the time CSR being readable from U-mode. On Linux this is the norm, but on some hardware a U-mode read traps and is emulated by M-mode/SBI, which would make the "fast" path slow. That's an inherent RISC-V platform assumption, the same class of assumption the aarch64 cntvct_el0 path already makes, so it's acceptable here.

Is there risk for non-RISC-V archs? No.

  • The new branch (lines 34-36) is an #elif guarded by defined(__riscv). __riscv is defined only by RISC-V toolchains and is mutually exclusive with __i386__/__x86_64__/__amd64__ and __aarch64__, so on x86/ARM/any other arch the preprocessor never reaches or evaluates it. C10_RISCVTSC is never defined there.
  • getRiscvApproximateTime() (lines 86-94) is wrapped in #if defined(C10_RISCVTSC), so it isn't even compiled off-RISC-V.
  • The #elif defined(C10_RISCVTSC) in getApproximateTime() (lines 109-110) is dead on other arches; their existing C10_RDTSC / C10_ARMTSC / getTime() selection is byte-for-byte unchanged.
  • CUDA/HIP are correctly excluded via !defined(__CUDACC__) && !defined(__HIPCC__), mirroring the aarch64 guard, so device compilation is unaffected.

Net: additive, well-scoped, and consistent with the existing aarch64 fast path from #178639. LGTM — consistent with ezyang's approval.
· branch riscv/approximate-clock-rdtime

@ezyang ezyang added the ciflow/trunk Trigger trunk jobs on your pull request label Jul 6, 2026
@ezyang

ezyang commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

mergedog handoff

All CI is green (or skipped). Ready for human review and @pytorchbot merge.

Current PR head: 30f354b815979453d2f83ade6f9acc49741010f7.
No mergedog-authored commits were pushed during this run.

CI notes at handoff

mergedog is treating these still-failing checks as unrelated/spurious. Please verify before merging:

  • linux-jammy-py3.10-clang18 / test-osdc (dynamo_wrapped, 2, 3, mt-l-x86iavx512-8-64)
  • pytorch-linux-noble-riscv64-py3_12-gcc14-cross-build / build-osdc

Warning: mergedog's suppressed check list differs from the latest Dr. CI summary.

Suppressed by mergedog but not marked unrelated by Dr. CI:

  • linux-jammy-py3.10-clang18 / test-osdc (dynamo_wrapped, 2, 3, mt-l-x86iavx512-8-64)
  • pytorch-linux-noble-riscv64-py3_12-gcc14-cross-build / build-osdc
Latest Dr. CI summary
## :link: Helpful Links
### :test_tube: See artifacts and rendered test results at [hud.pytorch.org/pr/189000](https://hud.pytorch.org/pr/189000)
* :page_facing_up: Preview [Python docs built from this PR](https://docs-preview.pytorch.org/pytorch/pytorch/189000/index.html)
* :page_facing_up: Preview [C++ docs built from this PR](https://docs-preview.pytorch.org/pytorch/pytorch/189000/cppdocs/index.html)
* :question: Need help or want to give feedback on the CI? Visit the [bot commands wiki](https://github.com/pytorch/pytorch/wiki/Bot-commands)

Note: Links to docs will display an error until the docs builds have been completed.


## :x: 1 New Failure, 1 Pending, 1 Unclassified Failure
As of commit 30f354b815979453d2f83ade6f9acc49741010f7 with merge base d12b917eef0b53c312017a060f7c690aec193592 (<sub><sub><img alt="image" width=70 src="https://img.shields.io/date/1783276397?label=&color=FFFFFF&style=flat-square"></sub></sub>):
<details open><summary><b>NEW FAILURE</b> - The following job has failed:</summary><p>

* [pull / linux-jammy-py3.10-clang18 / test-osdc (dynamo_wrapped, 2, 3, mt-l-x86iavx512-8-64)](https://hud.pytorch.org/pr/pytorch/pytorch/189000#85461417848) ([gh](https://github.com/pytorch/pytorch/actions/runs/28769179776/job/85461417848))
    `sccache: error: couldn't connect to server`
  <details><summary>AI verdict: <a href="https://hud.pytorch.org/pr/pytorch/pytorch/189000#85461417848"><img alt="AI verdict: not related" src="https://hud.pytorch.org/api/drci/advisorBadge?owner=pytorch&repo=pytorch&sha=30f354b815979453d2f83ade6f9acc49741010f7&job=pull+%2F+linux-jammy-py3.10-clang18+%2F+test-osdc+%28dynamo_wrapped%2C+2%2C+3%2C+mt-l-x86iavx512-8-64%29"></a></summary><blockquote>

  The failure is &quot;sccache: error: couldn&#39;t connect to server&quot; — a transient CI infrastructure issue where the shared compilation cache service was unreachable. The suspect commit only adds a RISC-V inline assembly path in a profiler utility, which cannot cause sccache connectivity problems.

  <a href="https://hud.pytorch.org/pr/pytorch/pytorch/189000#85461417848">Full reasoning on HUD &rarr;</a>
  </blockquote></details>
</p></details>
<details open><summary><b>UNCLASSIFIED FAILURE</b> - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:</summary><p>

* [riscv64 / pytorch-linux-noble-riscv64-py3_12-gcc14-cross-build / build-osdc](https://hud.pytorch.org/pr/pytorch/pytorch/189000#85459987107) ([gh](https://github.com/pytorch/pytorch/actions/runs/28817304405/job/85459987107)) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    `ModuleNotFoundError: No module named 'setuptools.command.bdist_wheel'`
  <details><summary>AI verdict: <a href="https://hud.pytorch.org/pr/pytorch/pytorch/189000#85459987107"><img alt="AI verdict: not related" src="https://hud.pytorch.org/api/drci/advisorBadge?owner=pytorch&repo=pytorch&sha=30f354b815979453d2f83ade6f9acc49741010f7&job=riscv64+%2F+pytorch-linux-noble-riscv64-py3_12-gcc14-cross-build+%2F+build-osdc"></a></summary><blockquote>

  The commit only adds a RISC-V #ifdef branch in a C++ header (c10/util/ApproximateClock.h). The failure is a Python setuptools environment error (&quot;No module named &#39;setuptools.command.bdist_wheel&#39;&quot;) in the riscv64 build job, which has been failing consistently in every run going back to May 2026 with various build environment issues.

  <a href="https://hud.pytorch.org/pr/pytorch/pytorch/189000#85459987107">Full reasoning on HUD &rarr;</a>
  </blockquote></details>
</p></details>


This comment was automatically generated by Dr. CI and updates every 15 minutes.

No LLM was invoked during this run.

@ezyang

ezyang commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 2 checks: pull / linux-jammy-py3.10-clang18 / test-osdc (dynamo_wrapped, 2, 3, mt-l-x86iavx512-8-64), riscv64 / pytorch-linux-noble-riscv64-py3_12-gcc14-cross-build / build-osdc

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

vishalgoyal316 pushed a commit to vishalgoyal316/pytorch that referenced this pull request Jul 16, 2026
## Summary

`getApproximateTime()` returns a cheap monotonic counter that the profiler calibrates against wall-clock time, avoiding a `clock_gettime` syscall on every timestamp. It uses `__rdtsc` on x86 and `cntvct_el0` on aarch64, but had **no RISC-V branch** — so on RISC-V every timestamp fell back to the `getTime()` syscall path, the slow path this mechanism exists to avoid.

This adds a RISC-V (rv64) fast path that reads the `time` CSR via `rdtime`, mirroring the aarch64 `cntvct_el0` path from pytorch#178639.

## Details

`rdtime` is a constant-frequency counter and is user-readable on Linux — the same assumption the aarch64 path already makes for `cntvct_el0`. The branch is gated on `__riscv_xlen == 64` because on RV32 `rdtime` returns only the low 32 bits, so RV32 correctly keeps the `getTime()` fallback.

**Alternative considered:** `rdcycle`. It counts core cycles, which vary with frequency scaling and are commonly privileged (trap) in user mode, so it is unsuitable for a wall-time approximation; `rdtime` is the right counter.

## Test plan

```
# riscv64 emits the rdtime fast path:
clang --target=riscv64-unknown-elf -march=rv64gc -ffreestanding -O2 -c harness.c
llvm-objdump -d harness.o        # getApproximateTime: c0102573  rdtime a0

# rv32 correctly keeps the syscall fallback (no rdtime, calls getTime):
clang --target=riscv32-unknown-elf -march=rv32gc -ffreestanding -O2 -c harness.c
llvm-objdump -dr harness.o       # no rdtime; R_RISCV_CALL_PLT getTime

# existing aarch64 path still compiles and runs (verified natively):
clang harness.c -o t && ./t      # rc=0
```

Part of the RISC-V enablement effort pytorch#180975 (Phase 1.3).

Pull Request resolved: pytorch#189000
Approved by: https://github.com/ezyang
DamJanusz pushed a commit to DamJanusz/pytorch that referenced this pull request Jul 21, 2026
## Summary

`getApproximateTime()` returns a cheap monotonic counter that the profiler calibrates against wall-clock time, avoiding a `clock_gettime` syscall on every timestamp. It uses `__rdtsc` on x86 and `cntvct_el0` on aarch64, but had **no RISC-V branch** — so on RISC-V every timestamp fell back to the `getTime()` syscall path, the slow path this mechanism exists to avoid.

This adds a RISC-V (rv64) fast path that reads the `time` CSR via `rdtime`, mirroring the aarch64 `cntvct_el0` path from pytorch#178639.

## Details

`rdtime` is a constant-frequency counter and is user-readable on Linux — the same assumption the aarch64 path already makes for `cntvct_el0`. The branch is gated on `__riscv_xlen == 64` because on RV32 `rdtime` returns only the low 32 bits, so RV32 correctly keeps the `getTime()` fallback.

**Alternative considered:** `rdcycle`. It counts core cycles, which vary with frequency scaling and are commonly privileged (trap) in user mode, so it is unsuitable for a wall-time approximation; `rdtime` is the right counter.

## Test plan

```
# riscv64 emits the rdtime fast path:
clang --target=riscv64-unknown-elf -march=rv64gc -ffreestanding -O2 -c harness.c
llvm-objdump -d harness.o        # getApproximateTime: c0102573  rdtime a0

# rv32 correctly keeps the syscall fallback (no rdtime, calls getTime):
clang --target=riscv32-unknown-elf -march=rv32gc -ffreestanding -O2 -c harness.c
llvm-objdump -dr harness.o       # no rdtime; R_RISCV_CALL_PLT getTime

# existing aarch64 path still compiles and runs (verified natively):
clang harness.c -o t && ./t      # rc=0
```

Part of the RISC-V enablement effort pytorch#180975 (Phase 1.3).

Pull Request resolved: pytorch#189000
Approved by: https://github.com/ezyang
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
## Summary

`getApproximateTime()` returns a cheap monotonic counter that the profiler calibrates against wall-clock time, avoiding a `clock_gettime` syscall on every timestamp. It uses `__rdtsc` on x86 and `cntvct_el0` on aarch64, but had **no RISC-V branch** — so on RISC-V every timestamp fell back to the `getTime()` syscall path, the slow path this mechanism exists to avoid.

This adds a RISC-V (rv64) fast path that reads the `time` CSR via `rdtime`, mirroring the aarch64 `cntvct_el0` path from pytorch#178639.

## Details

`rdtime` is a constant-frequency counter and is user-readable on Linux — the same assumption the aarch64 path already makes for `cntvct_el0`. The branch is gated on `__riscv_xlen == 64` because on RV32 `rdtime` returns only the low 32 bits, so RV32 correctly keeps the `getTime()` fallback.

**Alternative considered:** `rdcycle`. It counts core cycles, which vary with frequency scaling and are commonly privileged (trap) in user mode, so it is unsuitable for a wall-time approximation; `rdtime` is the right counter.

## Test plan

```
# riscv64 emits the rdtime fast path:
clang --target=riscv64-unknown-elf -march=rv64gc -ffreestanding -O2 -c harness.c
llvm-objdump -d harness.o        # getApproximateTime: c0102573  rdtime a0

# rv32 correctly keeps the syscall fallback (no rdtime, calls getTime):
clang --target=riscv32-unknown-elf -march=rv32gc -ffreestanding -O2 -c harness.c
llvm-objdump -dr harness.o       # no rdtime; R_RISCV_CALL_PLT getTime

# existing aarch64 path still compiles and runs (verified natively):
clang harness.c -o t && ./t      # rc=0
```

Part of the RISC-V enablement effort pytorch#180975 (Phase 1.3).

Pull Request resolved: pytorch#189000
Approved by: https://github.com/ezyang
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/riscv64 ciflow/trunk Trigger trunk jobs on your pull request Merged mergedog mergedog is watching this PR module: risc-v All issues related to RISC-V architecture open source topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants