From c1c0509280603339fe1ead856fbd96ca074450d1 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:08:00 -0500 Subject: [PATCH] perf(gpu): single-pass embedded PTX parse and reuse sha256 (#13639) * perf(gpu): single-pass embedded PTX parse and reuse decoded sha256 * fix(gpu): retain kernels yielded before malformed PTX --- src/gpu/GpuInventory.test.ts | 27 +++++++ src/gpu/GpuInventory.ts | 59 ++++++++++----- src/gpu/PtxKernels.ts | 138 ++++++++++++++++++++++------------- 3 files changed, 155 insertions(+), 69 deletions(-) diff --git a/src/gpu/GpuInventory.test.ts b/src/gpu/GpuInventory.test.ts index c21851400b..334ef47cc8 100644 --- a/src/gpu/GpuInventory.test.ts +++ b/src/gpu/GpuInventory.test.ts @@ -162,3 +162,30 @@ it("classifies an over-limit kernel symbol name as capacity", async () => { ]), }); }); + +it.each(["standalone", "embedded"] as const)( + "retains a valid %s PTX kernel before a malformed entry", + async (kind) => { + const ptx = Buffer.from( + ".version 8.8\n.target sm_80\n.entry good() { ret; }\n.entry broken(", + ); + const bytes = + kind === "standalone" + ? ptx + : cudaFixture("none", [{ kind: 1, target: 75, bytes: ptx }]); + const inventory = new GpuInventory({ + path: "/fixture", + analysis: "kernels", + }); + await inventory.inspect(new GpuBufferSource(bytes, "fixture")); + expect(inventory.objects.find(({ kind }) => kind === "ptx")).toMatchObject({ + inspection: "malformed", + payload_target: "sm_80", + }); + expect(inventory.kernels.map(({ name }) => name)).toEqual(["good"]); + if (kind === "embedded") + expect(inventory.kernels[0]?.limitations).toContain( + "Conflicting target declarations: inventory sm_75; payload sm_80. Target agreement is not established.", + ); + }, +); diff --git a/src/gpu/GpuInventory.ts b/src/gpu/GpuInventory.ts index 3911a27c09..40db91bf97 100644 --- a/src/gpu/GpuInventory.ts +++ b/src/gpu/GpuInventory.ts @@ -65,6 +65,7 @@ import { type AmdElfMetadata, } from "./GpuElfKernels.js"; import { + createPtxTargetTracker, ptxTargetIdentity, readPtxKernels, readPtxTarget, @@ -412,7 +413,8 @@ export class GpuInventory { ); } } - this.#decoded(row, sha256Hex(bytes), bytes.length); + const decodedSha256 = sha256Hex(bytes); + this.#decoded(row, decodedSha256, bytes.length); const decoded = new GpuBufferSource(bytes, row.id); if (row.kind === "ptx") { // Standalone discovery already retained this encoding failure. @@ -424,21 +426,10 @@ export class GpuInventory { const content = bytes.subarray(0, length); const text = standalonePtx?.text ?? readPtxText(content, "complete"); if (text === null) return rejectGpu(PTX_INVALID_UTF8); - const target = standalonePtx?.targetFacts ?? readPtxTarget(text); - const conflict = this.#target(row, { - value: target.target, - key: target.target, - scope: "exact", - ...(target.limitation === null - ? {} - : { limitation: target.limitation }), - }); - if (conflict !== undefined) coverage = "partial"; - const parsed = readPtxKernels(text, row.id); const artifact = { id: `${row.id}/ptx`, object_id: row.id, - sha256: sha256Hex(content), + sha256: length === bytes.length ? decodedSha256 : sha256Hex(content), media_type: "text/x-ptx" as const, encoding: "utf-8" as const, byte_length: content.length, @@ -447,12 +438,44 @@ export class GpuInventory { }; this.#retain(artifact); this.ptx_artifacts.push(artifact); - for (const { kernel, coverage: kernelCoverage } of parsed) { - if (conflict !== undefined) kernel.limitations.push(conflict); - if (kernelCoverage === "partial") coverage = "partial"; - this.#retain(kernel); - this.kernels.push(kernel); + // Extract target directives and kernel entries in a single token pass + // for embedded PTX; on a parse failure fall back to readPtxTarget so + // any target directives after a malformed entry are still preserved. + const tracker = + standalonePtx === undefined ? createPtxTargetTracker() : undefined; + const firstKernel = this.kernels.length; + const finishTarget = (target: ReturnType) => { + const limitation = this.#target(row, { + value: target.target, + key: target.target, + scope: "exact", + ...(target.limitation === null + ? {} + : { limitation: target.limitation }), + }); + if (limitation === undefined) return; + coverage = "partial"; + for (let index = firstKernel; index < this.kernels.length; index++) { + this.#retain([limitation]); + this.kernels[index]!.limitations.push(limitation); + } + }; + try { + for (const { kernel, coverage: kernelCoverage } of readPtxKernels( + text, + row.id, + tracker, + )) { + this.#retain(kernel); + this.kernels.push(kernel); + if (kernelCoverage === "partial") coverage = "partial"; + } + } catch (cause) { + if (!(cause instanceof GpuReportCapacityFailure)) + finishTarget(standalonePtx?.targetFacts ?? readPtxTarget(text)); + throw cause; } + finishTarget(standalonePtx?.targetFacts ?? tracker!.facts()); } else if (row.kind === "cubin" || row.kind === "amdgpu") { if (row.kind === "amdgpu" && isLlvmBitcode(bytes)) throw new BinaryFormatFailure("unsupported", LLVM_BITCODE_LIMITATION); diff --git a/src/gpu/PtxKernels.ts b/src/gpu/PtxKernels.ts index 81f10044d7..e653bf754e 100644 --- a/src/gpu/PtxKernels.ts +++ b/src/gpu/PtxKernels.ts @@ -297,6 +297,7 @@ const declaration = ( export function* readPtxKernels( text: string, objectId: string, + targetTracker?: PtxTargetTracker, ): Generator<{ kernel: GpuKernel; coverage: "complete" | "partial" }> { if (Buffer.byteLength(text) > GPU_REPORT_BYTES) throw new BinaryResourceFailure( @@ -313,8 +314,12 @@ export function* readPtxKernels( let kernelCount = 0; let outerDepth = 0; let version: PtxVersion | null = null; + let firstToken = true; + let targetTrackingEnabled = false; for (let step = iterator.next(); !step.done; step = iterator.next()) { const token = step.value; + const isFirst = firstToken; + firstToken = false; if (token.value === "{") { outerDepth++; continue; @@ -328,6 +333,16 @@ export function* readPtxKernels( if (token.value === ".version") { const value = iterator.next(); version = value.done ? null : ptxVersion(value.value.value); + if (isFirst) targetTrackingEnabled = version !== null; + continue; + } + if ( + targetTracker !== undefined && + targetTrackingEnabled && + token.value === ".target" + ) { + const value = iterator.next(); + targetTracker.observe(value.done ? undefined : value.value.value); continue; } if (token.value !== ".entry") continue; @@ -567,12 +582,78 @@ export function* readPtxKernels( if (outerDepth !== 0) rejectGpu("Unbalanced PTX body"); } -interface PtxTargetFacts { +export interface PtxTargetFacts { readonly recognized: boolean; readonly target: string | null; readonly limitation: string | null; } +/** Single-pass `.target` directive accumulator shared by target discovery and module parsing. */ +export interface PtxTargetTracker { + observe(spelling: string | undefined): void; + markMalformed(): void; + facts(): PtxTargetFacts; +} + +export const createPtxTargetTracker = (): PtxTargetTracker => { + let target: string | null = null, + targetIdentity: string | null = null, + targetArchitecture = -1, + ambiguous = false, + unsupported = false, + malformed = false; + return { + observe(spelling) { + if (spelling === undefined) { + unsupported = true; + return; + } + const match = /^(?:sm_|compute_)([0-9]+)(?:a|f)?$/u.exec(spelling); + if (match === null) { + unsupported = true; + return; + } + const architecture = Number(match[1]); + if (!Number.isSafeInteger(architecture)) { + unsupported = true; + return; + } + const identity = ptxTargetIdentity(spelling); + if (architecture > targetArchitecture) { + target = spelling; + targetIdentity = identity; + targetArchitecture = architecture; + ambiguous = false; + } else if ( + architecture === targetArchitecture && + targetIdentity !== identity + ) { + ambiguous = true; + } + }, + markMalformed() { + malformed = true; + }, + facts() { + const recognized = target !== null; + const limitation = !recognized + ? null + : unsupported + ? "Unsupported PTX target directives leave the effective target unknown." + : ambiguous + ? "Same-generation PTX target profiles cannot be represented by one effective target." + : malformed + ? "Malformed PTX text prevents complete target discovery." + : null; + return { + recognized, + target: limitation === null ? target : null, + limitation, + }; + }, + }; +}; + /** PTX's compute spelling is an alias for the corresponding baseline SM target. */ export const ptxTargetIdentity = (target: string): string => target.replace(/^compute_(\d+[a-z]?)$/u, "sm_$1"); @@ -580,13 +661,8 @@ export const ptxTargetIdentity = (target: string): string => /** Resolve all module-scope targets through the highest numbered architecture. */ export const readPtxTarget = (text: string): PtxTargetFacts => { const stream = tokens(text); - let depth = 0, - target: string | null = null, - targetIdentity: string | null = null, - targetArchitecture = -1, - ambiguous = false, - unsupported = false, - malformed = false; + const tracker = createPtxTargetTracker(); + let depth = 0; try { const first = stream.next(); if (first.done || first.value.value !== ".version") @@ -609,51 +685,11 @@ export const readPtxTarget = (text: string): PtxTargetFacts => { if (depth !== 0) continue; if (token.value !== ".target") continue; const value = stream.next(); - if (value.done) { - unsupported = true; - continue; - } - const spelling = value.value.value, - match = /^(?:sm_|compute_)([0-9]+)(?:a|f)?$/u.exec(spelling); - if (match === null) { - unsupported = true; - continue; - } - const architecture = Number(match[1]); - if (!Number.isSafeInteger(architecture)) { - unsupported = true; - continue; - } - const identity = ptxTargetIdentity(spelling); - if (architecture > targetArchitecture) { - target = spelling; - targetIdentity = identity; - targetArchitecture = architecture; - ambiguous = false; - } else if ( - architecture === targetArchitecture && - targetIdentity !== identity - ) { - ambiguous = true; - } + tracker.observe(value.done ? undefined : value.value.value); } } catch (cause) { if (!(cause instanceof BinaryFormatFailure)) throw cause; - malformed = true; + tracker.markMalformed(); } - const recognized = target !== null; - const limitation = !recognized - ? null - : unsupported - ? "Unsupported PTX target directives leave the effective target unknown." - : ambiguous - ? "Same-generation PTX target profiles cannot be represented by one effective target." - : malformed - ? "Malformed PTX text prevents complete target discovery." - : null; - return { - recognized, - target: limitation === null ? target : null, - limitation, - }; + return tracker.facts(); };