Skip to content

feat(bench): Record GPU state, sustain GEMM rounds, and flag round spread - #27

Merged
devin-ai-integration[bot] merged 4 commits into
mainfrom
devin/1791841790-gemm-gpu-state
Oct 12, 2026
Merged

devin-ai-integration[bot] merged 4 commits into
mainfrom
devin/1791841790-gemm-gpu-state

Conversation

@devin-ai-integration

Copy link
Copy Markdown
Contributor

Closes #5

Summary

  • GPU state per GEMM round. napkin-bench opens NVML (libnvidia-ml) at run time through nvml-wrapper 0.13. That's the same dynamic loading cudarc uses, and it adds no new unsafe. NVML resolves the CUDA device by PCI bus ID. While the GEMM rounds run, a second thread polls every 5 ms. Each round stores wall_ms, SM and memory clock spans, temperature, power from energy-counter ticks (null when the counter ticked fewer than twice), and how many polls saw each clock-limit reason. This is Measured.gpu_state (GpuState/RoundState/Span in napkin-profile). It is #[serde(default)], so older profiles still parse. napkin table prints a per-dtype state table, and AGENTS.md plus lint-arch.sh now allow napkin-bench to import those types.
  • Method change. Each GEMM dtype now runs untimed for 1 s, then times 7 rounds of about 200 ms (≈300 calls for an fp16 8192³ GEMM on B300). Before, it was 10 warm-up calls and 10-call rounds (~7–15 ms). The first batch is excluded from the warm-up and from round sizing, because on B300 it includes over a second of cuBLAS kernel loading. GpuState records warmup_ms/round_ms, and each round records its real wall_ms.
  • Visible spread. Measured::round_spread = slowest round / fastest round − 1. Cells whose rounds spread more than SPREAD_FLAG (5%) get †, and a footnote names the spreads. The footnote calls the spread an observed range of 7 rounds, not a confidence interval, and says the cell is the median round. The threshold is documented in the README methodology.

Investigation (H100!:2 first): power/clock hypothesis confirmed

Probes ran on H100!:2, driver 610.57.04, with 10-call rounds (the old method). Those hosts had PCIe gen4 links against a gen5 maximum, so pcie_full_link failed and none of their numbers are committed. The GEMM data from them is still valid evidence.

  • Old method, 7 rounds. fp16 ran 761, 761, 760, 694, 677, 680, 648 TFLOP/s, a 17.5% spread. The first three rounds were at the 1980 MHz max SM clock. sw_power_cap showed up from round 4 and the SM clock dropped. fp32 stayed at 52 TFLOP/s and 1980 MHz with no cap, 0.1% spread.
  • 150 back-to-back 10-call rounds. fp16 starts near 764 TFLOP/s at 1980 MHz for about 100 ms. sw_power_cap engages by about 170 ms. After that the SM clock moves between 1080 and 1500 MHz (548–731 TFLOP/s) for the whole run, a 39% spread. bf16 and tf32 behave the same. The temperature went from 35 to 53 °C and no thermal reason ever appeared.
  • Conclusion: confirmed. The drift is the board's software power cap moving the SM clock, and throughput follows the clock: 585 TFLOP/s at 1125 MHz, 719 at 1455. The old method mixed boost-clock rounds with capped rounds. A long GEMM (training or prefill) runs at the capped rate.
  • B300/B200 under the new method. The boost-clock bias was larger than the spread suggested. Sustained fp16 runs at about 1125 MHz of 2032 under sw_power_cap at the 1100 W limit, so the published B300 fp16 rate drops from 1700 to 1314 TFLOP/s. B200 fp16 runs at about 1050 of 1965 MHz at 1000 W, and drops from 1500 to 1251. With the sustained method, B200 and B300 rounds agree within 2%.
  • H100 under the new method. The spread is still 10–14% for fp16/bf16/tf32, because the power controller keeps moving the clock (1170–1470 MHz) on seconds-long timescales. That spread is real behaviour, so H100 keeps its † flag. I did not tune any constant to remove it.
  • Bug found while validating. On B300 the first GEMM batch takes over a second (cuBLAS lazy kernel loading). In my first version that batch ended the warm-up and sized each round at 10 calls (~7 ms), which hid the cap. Fixed in 5944ac9, and each round now records wall_ms.

Deviation from the issue: the 5% flag also fires for non-GEMM rows such as host copies and launch, because the README says "a metric's spread". Those rows have no clock state attached; their noise likely comes from host or PCIe effects (hypothesis, not investigated).

Runs

All on Modal, napkin-bench at this branch (sustained rounds, commit 5944ac9), CUDA 12.9, modal run modal/bench.py --gpu <gpu>. Every committed run has a full PCIe link:

GPU Request Captured Driver PCIe fp16 / bf16 / tf32 / fp32 TFLOP/s GEMM spread fp16/bf16/tf32/fp32
A100 A100-80GB:2 2026-10-12T22:23:47Z 610.57.04 gen4x16 / gen4x16 255 / 264 / 127 / 19 2.9 / 2.6 / 2.2 / 0.0%
H100 H100!:2 2026-10-12T22:23:05Z 580.95.05 gen5x16 / gen5x16 652 / 691 / 357 / 51 10.4 / 13.6 / 13.1 / 2.0%
B200 B200:2 2026-10-12T22:33:57Z 610.57.04 gen5x16 / gen5x16 1251 / 1325 / 684 / 66 1.6 / 1.7 / 0.8 / 0.0%
B300 B300:2 2026-10-12T22:26:52Z 610.57.04 gen6x16 / gen6x16 1314 / 1426 / 752 / 67 1.5 / 0.5 / 0.4 / 0.1%

Hosts with degraded links were rejected and rerun: H100 three times at gen4/gen5, and B300 three times reporting gen6 current against a gen5 host maximum. A separate-process pynvml probe on B300 confirmed NVML calls stay fast under load (energy counter p50 4 ms).

The README's hand-written cost example (1 EFLOP bf16 job) is updated for the new B200 rate: 750 s, $1.30 / $4.34, break-even 0.83 instead of 0.73. Its conclusion is unchanged.

Link to Devin session: https://app.devin.ai/sessions/de93f9e3a0d94c2ca7f3960d81528607
Open in Devin Desktop: https://app.devin.ai/desktop/session/de93f9e3a0d94c2ca7f3960d81528607?variant=devin
Requested by: @gpu004

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@socket-security

socket-security Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Addedcargo/​nvml-wrapper@​0.13.010010093100100

View full report

Awesome stuff and others added 4 commits October 12, 2026 22:39
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ounds

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration
devin-ai-integration Bot force-pushed the devin/1791841790-gemm-gpu-state branch from 78c16fe to dd7a97a Compare October 12, 2026 22:39
@devin-ai-integration
devin-ai-integration Bot merged commit 1afc063 into main Oct 12, 2026
4 checks passed
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

A100 host copies on main came from a half-speed host

profiles/a100.measured.json from this PR (864d425) reports H2D/D2H 12.3 / 13.1 GB/s on a Gen4 x16 link. Every earlier full-speed run measured about 26 GB/s.

What I confirmed

git log -- profiles/a100.measured.json, request A100-80GB:2 for every run:

commit driver H2D GB/s D2H GB/s
d107de3 / 246396f 580.95.05 26.47 26.30
53581a6 580.95.05 24.62 12.46
f5cdef7 (same file at 777b018) 580.95.05 26.27 26.07
67755d3 610.57.04 11.31 12.94
864d425 (main) 610.57.04 12.34 13.13
  • The current profile has pcie_gen = pcie_gen_max = 4 and pcie_width = pcie_width_max = 16, so pcie_full_link passed. That check compares only the negotiated gen and width with their maximums, not the bandwidth the link delivers (crates/napkin-bench/src/cuda.rs, the pcie_full_link insert).
  • Share of the theoretical per-direction link rate reached by the slower copy direction (Gen4 x16 = 31.51 GB/s, Gen5 x16 = 63.02 GB/s, B300 capped by host max Gen5):
    • A100 on main: 39.2%
    • H100: 85.1%
    • B200: 88.2%
    • B300: 88.3%
    • earlier 580-host A100 runs: about 83%
  • 53581a6 shows a host can also be slow in one direction only (D2H 12.46 GB/s).

Hypothesis (not verified)

The slow runs all landed on driver 610.57.04 hosts. I think that points to a different Modal host pool, not to the driver itself. I haven't tested driver 610 on a fast host or 580 on a slow one, and Modal's gVisor sandbox exposes no lspci or nvidia-smi topo to tell the hosts apart. Host memcpy on the 864d425 host was 40 GB/s, but 67755d3 had a slow PCIe link with a normal 60 GB/s host memcpy, so host memory doesn't explain it either.

Proposed guard (patch below, not pushed)

  • napkin-profile: adds Measured::pcie_link_gbps(), the theoretical per-direction rate of the effective gen × width.
  • napkin-profile: adds Measured::pcie_link_at_speed(), which requires min(h2d, d2h) >= 0.7 × that rate (PCIE_MIN_LINK_FRACTION).
  • napkin-bench: records it as the pcie_link_bandwidth check, so a slow host makes the run fail and writes no profile.
  • build.rs: rejects any committed profile below the floor, even older ones without the check key.
  • Tests in crates/napkin/src/profile.rs, plus one README sentence.

With the patch applied, cargo check -p napkin fails on the current A100 profile with the new diagnostic, as intended. H100, B200 and B300 pass. cargo test -p napkin-profile and cargo check -p napkin-bench --all-targets pass. I couldn't commit it: the prek hooks build napkin, and the build now rejects the A100 profile. I didn't bypass the hooks.

Blocked on

Re-running the A100 calibration (modal run modal/bench.py --gpu a100, retried until a host passes) needs Modal access:

  • the tusharhqq workspace hit its spend limit ("Workspace … has exceeded its spend limit")
  • the old tushardzig token fails validation because it was rotated
  • the token flow I started for tushardzig expired before anyone approved it

Next steps

  1. Restore Modal access.
  2. Apply the patch and re-run the A100 calibration until pcie_link_bandwidth passes.
  3. Run cargo run -p napkin -- readme --write README.md PROBLEMS.md, then the prek gate.
  4. Open the PR.
Patch (git diff against main b09c64b)
diff --git a/README.md b/README.md
index 5e70ffe..b074fa6 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,9 @@ Host copies ran on A100 at PCIe Gen4 x16, and H100 and B200 at Gen5 x16. B300's
 GPU link trains at Gen6 x16, but `nvidia-smi` reports `Host Max: 5`: each HGX
 B300 GPU connects at Gen6 to the PCIe switch inside its ConnectX-8 NIC, then
 Gen5 x16 to the CPU. B300 host copies are therefore Gen5-bound, like B200 and
-H100.
+H100. A benchmark also rejects a host link when its slower copy direction
+delivers less than 70% of the effective PCIe rate, allowing for packet overhead
+while catching links that negotiate full speed but transfer at about half rate.
 
 **Note 1:** Compute figures are dense, not sparse. NVIDIA's headline Tensor
 Core numbers assume structured sparsity; dense is half.
diff --git a/crates/napkin-bench/src/cuda.rs b/crates/napkin-bench/src/cuda.rs
index fa9441a..1c4f234 100644
--- a/crates/napkin-bench/src/cuda.rs
+++ b/crates/napkin-bench/src/cuda.rs
@@ -1062,9 +1062,7 @@ pub(crate) fn run(cfg: &Config, gpu_request: &str) -> Result<Measured, BenchErro
     let (cc_major, cc_minor) = ctx0.compute_capability()?;
     let sm_count =
         ctx0.attribute(dsys::CUdevice_attribute::CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT)?;
-    let all_ok = checks.values().all(|v| *v);
-
-    Ok(Measured {
+    let mut measured = Measured {
         captured_at: crate::iso_now(),
         gpu_request: if cfg.quick {
             format!("{gpu_request} --quick")
@@ -1110,26 +1108,45 @@ pub(crate) fn run(cfg: &Config, gpu_request: &str) -> Result<Measured, BenchErro
                 .state(cfg.gemm_warmup, cfg.gemm_round, gemm_states)
                 .map_err(BenchError)?,
         ),
-    })
-    .and_then(|m| {
-        if all_ok {
-            Ok(m)
-        } else {
-            eprintln!(
-                "FAILED CHECKS: {:?}",
-                m.checks
-                    .iter()
-                    .filter(|(_, v)| !**v)
-                    .map(|(k, _)| k)
-                    .collect::<Vec<_>>()
-            );
-            println!(
-                "{}",
-                serde_json::to_string_pretty(&m).map_err(|e| BenchError(e.to_string()))?
-            );
-            Err(BenchError(
-                "one or more correctness checks failed".to_owned(),
-            ))
-        }
-    })
+    };
+    if let Some(link_gbps) = measured.pcie_link_gbps()
+        && let Some(at_speed) = measured.pcie_link_at_speed()
+    {
+        let fraction = measured.h2d_gbps.min(measured.d2h_gbps) / link_gbps;
+        progress(
+            "pcie bandwidth",
+            &format!(
+                "{:.1}/{:.1} GB/s = {:.0}% of {:.1} GB/s link",
+                measured.h2d_gbps,
+                measured.d2h_gbps,
+                fraction * 100.0,
+                link_gbps,
+            ),
+        );
+        measured
+            .checks
+            .insert("pcie_link_bandwidth".to_owned(), at_speed);
+    }
+
+    if measured.checks.values().all(|passed| *passed) {
+        Ok(measured)
+    } else {
+        eprintln!(
+            "FAILED CHECKS: {:?}",
+            measured
+                .checks
+                .iter()
+                .filter(|(_, passed)| !**passed)
+                .map(|(name, _)| name)
+                .collect::<Vec<_>>()
+        );
+        println!(
+            "{}",
+            serde_json::to_string_pretty(&measured)
+                .map_err(|error| BenchError(error.to_string()))?
+        );
+        Err(BenchError(
+            "one or more correctness checks failed".to_owned(),
+        ))
+    }
 }
diff --git a/crates/napkin-profile/src/lib.rs b/crates/napkin-profile/src/lib.rs
index 9479a70..585cc89 100644
--- a/crates/napkin-profile/src/lib.rs
+++ b/crates/napkin-profile/src/lib.rs
@@ -283,6 +283,13 @@ pub struct Span {
     pub max: f64,
 }
 
+/// Minimum fraction of theoretical `PCIe` rate accepted for host copies.
+///
+/// Healthy hosts reach about 83–91% of raw link rate after packet overhead;
+/// 70% rejects links that negotiate full speed but deliver about half of it,
+/// as on the A100 driver-610 host (12.3 GB/s over Gen4 x16).
+pub const PCIE_MIN_LINK_FRACTION: f64 = 0.7;
+
 impl Measured {
     /// Returns the `PCIe` generation available for host↔device transfers.
     #[must_use]
@@ -292,6 +299,29 @@ impl Measured {
                 .map_or(generation, |host_max| generation.min(host_max))
         })
     }
+
+    /// Returns the theoretical per-direction rate of the effective `PCIe`
+    /// link in GB/s.
+    #[must_use]
+    pub fn pcie_link_gbps(&self) -> Option<f64> {
+        let per_lane_gbps = match self.pcie_effective_gen()? {
+            1 => 0.25,
+            2 => 0.5,
+            3 => 8.0 * 128.0 / 130.0 / 8.0,
+            4 => 16.0 * 128.0 / 130.0 / 8.0,
+            5 => 32.0 * 128.0 / 130.0 / 8.0,
+            6 => 8.0,
+            _ => return None,
+        };
+        Some(per_lane_gbps * f64::from(self.pcie_width?))
+    }
+
+    /// Whether both measured host-copy directions reach the minimum share of
+    /// the effective link rate, or None when the link rate cannot be derived.
+    #[must_use]
+    pub fn pcie_link_at_speed(&self) -> Option<bool> {
+        Some(self.h2d_gbps.min(self.d2h_gbps) >= PCIE_MIN_LINK_FRACTION * self.pcie_link_gbps()?)
+    }
 }
 
 /// Where a rate came from.
diff --git a/crates/napkin/build.rs b/crates/napkin/build.rs
index 95e26e4..984bb48 100644
--- a/crates/napkin/build.rs
+++ b/crates/napkin/build.rs
@@ -452,6 +452,14 @@ fn validate_ceiling(id: &str, ceiling: &Ceiling) -> Result<(), String> {
 }
 
 fn validate_measured(id: &str, measured: &Measured) -> Result<(), String> {
+    if measured.pcie_link_at_speed() == Some(false)
+        && let Some(link_gbps) = measured.pcie_link_gbps()
+    {
+        return Err(format!(
+            "measured profile {id:?} is below the PCIe bandwidth floor: H2D {:.1} GB/s, D2H {:.1} GB/s, effective link {:.2} GB/s (70% floor); re-run `modal run modal/bench.py --gpu {id}` on another host",
+            measured.h2d_gbps, measured.d2h_gbps, link_gbps
+        ));
+    }
     if let Some((name, _)) = measured.checks.iter().find(|(_, passed)| !**passed) {
         return Err(format!(
             "measured profile {id:?} has failing check {name:?}"
diff --git a/crates/napkin/src/profile.rs b/crates/napkin/src/profile.rs
index be786d7..66db999 100644
--- a/crates/napkin/src/profile.rs
+++ b/crates/napkin/src/profile.rs
@@ -87,6 +87,63 @@ mod tests {
         }
     }
 
+    #[test]
+    fn pcie_link_gbps_uses_effective_generation_and_width() {
+        let parsed = serde_json::from_str::<napkin_profile::Measured>(include_str!(
+            "../../../profiles/h100.measured.json"
+        ));
+        assert!(parsed.is_ok(), "H100 measured profile fixture parses");
+        if let Ok(mut measured) = parsed {
+            measured.pcie_gen = Some(4);
+            measured.pcie_gen_host_max = Some(4);
+            measured.pcie_width = Some(16);
+            assert!(
+                measured
+                    .pcie_link_gbps()
+                    .is_some_and(|rate| (rate - 31.51).abs() < 0.01)
+            );
+
+            measured.pcie_gen = Some(6);
+            measured.pcie_gen_host_max = Some(5);
+            assert!(
+                measured
+                    .pcie_link_gbps()
+                    .is_some_and(|rate| (rate - 63.02).abs() < 0.01)
+            );
+
+            measured.pcie_gen = None;
+            assert_eq!(measured.pcie_link_gbps(), None);
+            measured.pcie_gen = Some(4);
+            measured.pcie_width = None;
+            assert_eq!(measured.pcie_link_gbps(), None);
+        }
+    }
+
+    #[test]
+    fn pcie_link_at_speed_checks_the_slower_direction() {
+        let parsed = serde_json::from_str::<napkin_profile::Measured>(include_str!(
+            "../../../profiles/h100.measured.json"
+        ));
+        assert!(parsed.is_ok(), "H100 measured profile fixture parses");
+        if let Ok(mut measured) = parsed {
+            measured.pcie_gen = Some(4);
+            measured.pcie_gen_host_max = Some(4);
+            measured.pcie_width = Some(16);
+
+            measured.h2d_gbps = 26.3;
+            measured.d2h_gbps = 26.1;
+            assert_eq!(measured.pcie_link_at_speed(), Some(true));
+
+            measured.h2d_gbps = 12.3;
+            measured.d2h_gbps = 13.1;
+            assert_eq!(measured.pcie_link_at_speed(), Some(false));
+
+            measured.h2d_gbps = 26.3;
+            measured.d2h_gbps = 12.4;
+            assert_eq!(measured.pcie_link_at_speed(), Some(false));
+        }
+    }
+
     #[test]
     fn measured_json_without_gpu_state_parses() {
         let mut json: serde_json::Value =

Written by Devin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

modal_benchmark: H100 tensor-core GEMM rounds drift 11-14% within one run; clocks and power are not recorded

1 participant