Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
b0cdc70
qwen3-asr: host config, tensor map, mel rows and a float64 tower (#2105)
jschmied Nov 5, 2026
00e0ae7
qwen3-asr: the tower and Qwen3 schedules, generic over a backend bind…
jschmied Nov 5, 2026
42344da
qwen3-asr case tool: each greedy step's top two and margin, and an id…
jschmied Nov 5, 2026
4b2fca4
qwen3-asr case tool: layer 0's steps as stages (#2105)
jschmied Nov 5, 2026
e04071f
qwen3-asr: the CUDA binding, tower and Qwen3 LM, greedy on one stream…
jschmied Nov 5, 2026
7e5a768
Follow main extracted CUDA help for the original ASR contract command
ashhart Nov 21, 2026
c4d4200
qwen3-asr: zig fmt
jschmied Nov 5, 2026
8efe483
qwen3-asr: mel.zig's comments describe the computation, not the refer…
jschmied Nov 5, 2026
92002e4
qwen3-asr: a lone chunk under 100 frames is convolved at its own leng…
jschmied Nov 6, 2026
afb65ef
qwen3-asr: tf-qwen3-asr-check opens a sharded checkpoint through core…
jschmied Nov 6, 2026
c8fae45
qwen3-asr: the host and CUDA checks are gates with a non-zero exit (#…
jschmied Nov 6, 2026
235b1bc
qwen3-asr: admission requires the tower's rows at the LM's width and …
jschmied Nov 6, 2026
79a1cbb
qwen3-asr: drop prompt.split, which claimed parse_asr_output without …
jschmied Nov 6, 2026
841d2e8
qwen3-asr: tf-qwen3-asr-check --ids-only, as tf-qwen3-asr has (#2105)
jschmied Nov 6, 2026
3e648eb
qwen3-asr: the tower dumps conv_out, and tf-qwen3-asr compares it (#2…
jschmied Nov 6, 2026
09d6b19
qwen3-asr: windowed attention is the decision, and a --global-attenti…
jschmied Nov 6, 2026
18650a6
qwen3-asr: one-line comments for the lean check (#2105)
jschmied Nov 6, 2026
a9270bd
qwen3-asr: a decode step's logits equal the prompt pass's rows, and a…
jschmied Nov 10, 2026
f575205
qwen3-asr: tf-qwen3-asr-forced, the teacher-forced tie rule, and the …
jschmied Nov 10, 2026
7b361da
qwen3-asr: tf-qwen3-asr-forced takes an exact reference tie either wa…
jschmied Nov 10, 2026
0f4ac86
qwen3-asr: the exact-tie order of the reference's topk pair moves int…
jschmied Nov 10, 2026
aad03f1
qwen3-asr: the language model runs qwen3's CUDA pass (#2285) with a s…
jschmied Nov 12, 2026
83dd8c3
qwen3 cuda: forwardFrom refuses a start or head without one input and…
jschmied Nov 12, 2026
d5a2f81
tests: re-pin prefill_attention.cu, vit.cu and vit.zig for Qwen3-ASR'…
jschmied Nov 12, 2026
970ad6a
tests/cuda: Qwen3-ASR's contract set runs under kernel-contract's wor…
jschmied Nov 17, 2026
f0eb1c6
Follow main extracted CUDA help when the original ASR command retires
ashhart Nov 21, 2026
9aa1420
qwen3-asr: tower_ref.zig's header and chunks.zig's rows test describe…
jschmied Nov 17, 2026
1fa23a8
changelog: #2239 under Unreleased
ashhart Nov 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- Qwen3-ASR on CUDA (tools only, not served yet): `tf-qwen3-asr` runs a WAV clip through the 0.6B or 1.7B checkpoint (the audio tower, then greedy decode through the Qwen3 CUDA pass the embedding engine runs), `tf-qwen3-asr-forced` teacher-forces a clip on a reference case, and `test-qwen3-asr-host` and `tf-qwen3-asr-check` cover config admission, tensor names, log-mel rows and a float64 tower without a GPU (#2239, refs #2105). Thanks to @jschmied.

- GLM TP=2 prefill on CUDA: `TF_GLM_INDEX_SPLIT=32768` keeps indexer scores, pools and token rows local on each rank below that position (no blocking all-gathers) and own partials are read in place; outputs are unchanged and the default stays 2048 (#4510).

- GLM at TP=2 on CUDA prefill: dense attention runs only on the rows sparse attention leaves untouched when a chunk crosses the dense limit, and prefill skips projections nothing reads (MTP proposal and query-side work); outputs are unchanged (#4499).
Expand Down
1 change: 1 addition & 0 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ pub fn build(b: *std.Build) void {
@import("zig/build/flashnext_budget.zig").steps(b, test_step);
@import("zig/build/flashnext_batch_host.zig").tests(b, test_step);
@import("zig/build/lfm3_host.zig").steps(b, test_step);
@import("zig/build/qwen3_asr_host.zig").steps(b, test_step);
if (b.graph.host.result.os.tag == .macos) {
const budget_mods = metalEngineModules(b, b.graph.host, .Debug, draft_ids);
const budget_empty = b.addWriteFiles().add("budget-compile-only.metallib", "");
Expand Down
130 changes: 130 additions & 0 deletions tools/zig/qwen3_asr_case.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
"""Qwen3-ASR's per-stage tensors from qwen-asr 0.0.6's transformers backend: tf-qwen3-asr's reference case."""
# usage: python3 -I tools/zig/qwen3_asr_case.py MODEL_DIR CLIP.wav OUT_DIR [--tokens N]; float32/int32 files a stage

import argparse
import json
import os
import sys

import numpy as np
import soundfile as sf
import torch


def save(out, manifest, name, t, kind="f32"):
kept = ("prompt_ids", "greedy_ids", "greedy_top2", "greedy_margin", "logits_bf16", "logits_fp32")
if manifest.get("ids_only") and name not in kept:
return
a = t.detach().to(torch.float32 if kind == "f32" else torch.int32).cpu().numpy()
a.astype("<f4" if kind == "f32" else "<i4").tofile(os.path.join(out, name + ".bin"))
manifest["stages"][name] = {"shape": list(a.shape), "dtype": kind}


def main():
p = argparse.ArgumentParser()
p.add_argument("model")
p.add_argument("clip")
p.add_argument("out")
p.add_argument("--tokens", type=int, default=256)
p.add_argument("--ids-only", action="store_true", help="only the prompt, greedy ids and margins: no stage tensors")
p.add_argument("--global-attention", action="store_true", help="the transformers backend as is: no windows")
p.add_argument("--logits", action="store_true", help="each greedy step's logits, teacher-forced, in bf16 and fp32")
a = p.parse_args()
torch.set_default_dtype(torch.bfloat16)
from qwen_asr import Qwen3ASRModel

os.makedirs(a.out, exist_ok=True)
asr = Qwen3ASRModel.from_pretrained(a.model, dtype=torch.bfloat16, device_map="cpu", max_new_tokens=a.tokens)
# bf16 only while loading: under it the feature extractor's hann window and STFT run in bf16 too
torch.set_default_dtype(torch.float32)
model, proc = asr.model, asr.processor
model.eval()
wav, sr = sf.read(a.clip, dtype="float32")
if sr != 16000 or wav.ndim != 1:
sys.exit("want a 16 kHz mono clip")
manifest = {"clip": os.path.basename(a.clip), "samples": int(wav.shape[0]), "stages": {}, "ids_only": a.ids_only}
prompt = asr._build_text_prompt(context="", force_language=None)
inputs = proc(text=[prompt], audio=[wav], return_tensors="pt", padding=True)
feats = inputs["input_features"][0]
flen = int(inputs["feature_attention_mask"][0].sum())
manifest["frames"] = flen
save(a.out, manifest, "mel", feats[:, :flen])
tower = model.thinker.audio_tower
taps = {}

def tap(name):
def hook(_m, args, out):
taps.setdefault(name, []).append(out[0] if isinstance(out, tuple) else out)
return hook

def windows(_m, args, kwargs):
# the vLLM backend's (and flash-attention-2's) windows: sdpa here gets no mask and attends over every row
hidden, cu = args[0], args[1]
kwargs["attention_mask"] = tower._prepare_attention_mask(hidden, cu)
return args, kwargs

def tap_in(name):
def hook(_m, args):
taps.setdefault(name, []).append(args[0])
return hook

hooks = [tower.conv2d1.register_forward_hook(tap("conv1")), tower.conv2d2.register_forward_hook(tap("conv2")),
tower.conv2d3.register_forward_hook(tap("conv3")), tower.conv_out.register_forward_hook(tap("conv_out")),
tower.layers[0].register_forward_pre_hook(tap_in("embed")), tower.ln_post.register_forward_hook(tap("ln_post")),
tower.proj1.register_forward_hook(tap("proj1")), tower.proj2.register_forward_hook(tap("audio_rows"))]
windowed = [] if a.global_attention else [x.register_forward_pre_hook(windows, with_kwargs=True) for x in tower.layers]
for i, layer in enumerate(tower.layers):
hooks.append(layer.register_forward_hook(tap(f"layer{i}")))
lm = model.thinker.model
manifest["attention"] = "global" if a.global_attention else "windows"
hooks.append(lm.layers[0].register_forward_pre_hook(tap_in("lm_embed")))
hooks.append(lm.norm.register_forward_hook(tap("lm_norm")))
l0 = lm.layers[0] # layer 0's steps: a wrong LM stage is found inside its first layer
hooks += [l0.input_layernorm.register_forward_hook(tap("lm0_norm")), l0.self_attn.o_proj.register_forward_pre_hook(tap_in("lm0_attn")),
l0.self_attn.o_proj.register_forward_hook(tap("lm0_o")), l0.post_attention_layernorm.register_forward_hook(tap("lm0_post")),
l0.mlp.register_forward_hook(tap("lm0_mlp"))]
for i in (0, len(lm.layers) // 2, len(lm.layers) - 1):
hooks.append(lm.layers[i].register_forward_hook(tap(f"lm_layer{i}")))
raw = dict(inputs) # the fp32 features, for the fp32 run
inputs = inputs.to(model.dtype)
with torch.no_grad():
gen = model.generate(**inputs, max_new_tokens=a.tokens, output_scores=True)
for h in hooks:
h.remove()
for name in ("conv1", "conv2", "conv3", "conv_out"):
save(a.out, manifest, name, torch.cat(taps[name], 0))
for name in ["embed"] + [f"layer{i}" for i in range(len(tower.layers))] + ["ln_post", "proj1", "audio_rows"]:
save(a.out, manifest, name, taps[name][0])
ids = inputs["input_ids"][0]
save(a.out, manifest, "prompt_ids", ids, "i32")
for name in [k for k in taps if k.startswith("lm")]:
save(a.out, manifest, name, taps[name][0][0])
new = gen.sequences[0, ids.shape[0]:]
save(a.out, manifest, "greedy_ids", new, "i32")
# each step's two best logits: a differing transcript is listed with the reference's margin where it differs
scores = torch.stack([s[0].float() for s in gen.scores], 0)
top = scores.topk(2, dim=-1)
save(a.out, manifest, "greedy_top2", top.indices, "i32")
save(a.out, manifest, "greedy_margin", top.values[:, 0] - top.values[:, 1])
if a.logits: # one pass over the prompt and the reply: step i's row is the one before greedy id i
full = torch.cat([ids, new[:-1]])[None]
rows = slice(ids.shape[0] - 1, ids.shape[0] - 1 + new.shape[0])
for kind, feats_in in (("bf16", inputs["input_features"]), ("fp32", None)):
if feats_in is None:
model.float()
feats_in = raw["input_features"].float()
with torch.no_grad():
out = model.thinker(input_ids=full, input_features=feats_in, attention_mask=torch.ones_like(full),
feature_attention_mask=inputs["feature_attention_mask"])
save(a.out, manifest, "logits_" + kind, out.logits[0, rows].float())
for h in windowed:
h.remove()
manifest["text"] = proc.batch_decode([new], skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
manifest["torch"] = torch.__version__
with open(os.path.join(a.out, "manifest.json"), "w") as f:
json.dump(manifest, f, indent=1)
print(json.dumps({"frames": flen, "tokens": int(new.shape[0]), "text": manifest["text"]}))


if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions zig/build/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu
b.getInstallStep().dependOn(&q35_install.step);
b.step("qwen35-cuda", "Build the Qwen CUDA forward and raw state receipt tool").dependOn(&q35_install.step);
@import("moss_image_tools.zig").install(b, target, optimize, strip, cuda, mods.core);
@import("qwen3_asr_cuda.zig").tool(b, target, optimize, cuda, mods.core, mods.tokenizer, strip);
const d3_tool = b.createModule(.{ .root_source_file = b.path("zig/src/families/drama3/generate.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "core", .module = mods.core }, .{ .name = "drama3", .module = @import("drama3_host.zig").module(b, target, optimize, cuda, mods.core) } } });
const d3_exe = b.addExecutable(.{ .name = "drama3-generate", .root_module = d3_tool });
b.step("drama3-generate", "Drama generation and replay controls on CUDA").dependOn(&b.addInstallArtifact(d3_exe, .{}).step);
Expand Down
16 changes: 16 additions & 0 deletions zig/build/qwen3_asr_cuda.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//! tf-qwen3-asr and tf-qwen3-asr-forced: Qwen3-ASR's tower and language model on CUDA against a reference case.
const std = @import("std");

pub fn tool(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module, tokenizer: *std.Build.Module, strip: ?bool) void {
// the Qwen3 layers: qwen3's CUDA pass, the one the embedding engine runs
const pass = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen3/pass_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core } } });
const family = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen3_asr/qwen3_asr_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core }, .{ .name = "qwen3_pass", .module = pass } } });
const main = b.createModule(.{ .root_source_file = b.path("zig/tests/qwen3_asr_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "qwen3_asr", .module = family }, .{ .name = "tokenizer", .module = tokenizer } } });
const exe = b.addExecutable(.{ .name = "tf-qwen3-asr", .root_module = main });
b.installArtifact(exe);
b.step("tf-qwen3-asr", "Build tf-qwen3-asr, Qwen3-ASR's CUDA tower and language model on a clip").dependOn(&b.addInstallArtifact(exe, .{}).step);
const forced = b.createModule(.{ .root_source_file = b.path("zig/tests/qwen3_asr_forced.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "qwen3_asr", .module = family } } });
const forced_exe = b.addExecutable(.{ .name = "tf-qwen3-asr-forced", .root_module = forced });
b.installArtifact(forced_exe);
b.step("tf-qwen3-asr-forced", "Build tf-qwen3-asr-forced, a clip teacher-forced on a case under the tie rule").dependOn(&b.addInstallArtifact(forced_exe, .{}).step);
}
25 changes: 25 additions & 0 deletions zig/build/qwen3_asr_host.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
//! Qwen3-ASR's host parts: config, tensors, mel rows and the float64 tower, no GPU.
const std = @import("std");

pub fn steps(b: *std.Build, all: *std.Build.Step) void {
const host = b.graph.host;
const family = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen3_asr/qwen3_asr.zig"), .target = host, .link_libc = true });
const checks = b.step("test-qwen3-asr-host", "Qwen3-ASR config, tensor names, mel rows and reference ops");
checks.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = family })).step);
all.dependOn(checks);
const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = host, .link_libc = true });
// core for its Checkpoint: a folder's shards (the 1.7B's two) as one name space, as the CUDA load opens them
const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = host, .link_libc = true });
core.addImport("gpu_memory", @import("gpu_memory.zig").module(b, host));
core.addImport("tokenizer", tokenizer);
const tool = b.addExecutable(.{ .name = "tf-qwen3-asr-check", .root_module = b.createModule(.{
.root_source_file = b.path("zig/qwen3_asr_check.zig"),
.target = host,
.optimize = .ReleaseFast,
.link_libc = true,
.imports = &.{ .{ .name = "qwen3_asr", .module = family }, .{ .name = "core", .module = core }, .{ .name = "tokenizer", .module = tokenizer } },
}) });
b.installArtifact(tool);
b.step("tf-qwen3-asr-check", "Check a Qwen3-ASR checkpoint and its float64 tower against a tools/zig/qwen3_asr_case.py case")
.dependOn(&b.addInstallArtifact(tool, .{}).step);
}
4 changes: 2 additions & 2 deletions zig/dense_serving_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ test "dense serving: owned CUDA images retain their reviewed lane and decode byt
try std.testing.expectEqualStrings("5f325dc6d8134624b30b5e99c5764f75beb3c344b5f949d38bfaa41bc8dfe5dc", &hash(@embedFile("kernels/cuda/experts_prefill.cu")));
try std.testing.expectEqualStrings("e5ef9dcce75c478e59e476d2fa8747baee2317bd283b0756f125ea050dad9228", &hash(@embedFile("kernels/cuda/gdn.cu")));
try std.testing.expectEqualStrings("dba5aae94115571ed48933d80f646fff31b2a7da226569867c74a1dc061d2ca2", &hash(@embedFile("kernels/cuda/lane_gemv.cu")));
// 191061381's bytes: 82f3dde92 and 191061381 (#2609) add pattn_kernel instances; 94a9a48d6 moves helpers out
try std.testing.expectEqualStrings("905fff2c9018d778557a60ed2c81c24ce220adf5b092c8c32f8a1782963f9f28", &hash(@embedFile("kernels/cuda/prefill_attention.cu")));
// #2239 adds vision_kernel<64, 8> for Qwen3-ASR's tower; every function main had keeps its SASS (sm_80 to sm_121)
try std.testing.expectEqualStrings("4227f0a9b7a89ac296388a7dcd9e49cd0dd487ed09ee46cc1d4eda94ab8e3741", &hash(@embedFile("kernels/cuda/prefill_attention.cu")));
const group = @embedFile("kernels/cuda/qmm_group.cu");
try std.testing.expectEqualStrings("ceff4ee13e97b5aa93cbe7a1edc9a524c78aaa145dd1e5c82dcb05a3011aae23", &hash(group[0..16095]));
try std.testing.expectEqualStrings("8780fd710be3ce2f04e53fa1e69eb062809d3bec6391d9bd49983d0588e374d0", &hash(group));
Expand Down
1 change: 1 addition & 0 deletions zig/kernels/cuda/contract_controls_set.cu
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@
#include "contract_hcn_controls.cuh"
// Idol decoders: controls for rounding, sums and exceptional values.
#include "contract_controls_idol_decoder.cuh"
#include "contract_qwen3_asr_controls.cuh"
33 changes: 33 additions & 0 deletions zig/kernels/cuda/contract_qwen3_asr_controls.cuh
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Gate 3: vit.cu's conv taps and flatten for Qwen3-ASR's tower, each with one planted fault the shapes gate must catch.
#pragma once

// tf_vit_conv_cols reading the clamped edge sample where the conv's padding is zero.
extern "C" __global__ void __launch_bounds__(256) tf_ctl_vit_conv_cols_edge(const __nv_bfloat16* __restrict__ X,
__nv_bfloat16* __restrict__ Y, int fi, int ti,
int c, int ld) {
const int fo = (fi - 1) / 2 + 1, to = (ti - 1) / 2 + 1;
const int64_t r = blockIdx.x;
const int64_t n = r / (static_cast<int64_t>(fo) * to);
const int f = static_cast<int>(r / to % fo), t = static_cast<int>(r % to);
const int j = blockIdx.y * 256 + threadIdx.x;
if (j >= ld) return;
__nv_bfloat16 v = __float2bfloat16_rn(0.0f);
if (j < 9 * c) {
const int ci = j / 9, kh = j % 9 / 3, kw = j % 3;
const int sf = min(max(2 * f - 1 + kh, 0), fi - 1), st = min(max(2 * t - 1 + kw, 0), ti - 1);
v = X[((n * fi + sf) * ti + st) * c + ci];
}
Y[r * ld + j] = v;
}

// tf_vit_conv_flatten writing a row f-major (f c + ci) where torch flattens [c][f] (ci f + fb).
extern "C" __global__ void __launch_bounds__(256) tf_ctl_vit_conv_flatten_fc(const __nv_bfloat16* __restrict__ X,
__nv_bfloat16* __restrict__ Y, int f, int t,
int c) {
const int64_t row = blockIdx.x, n = row / t;
const int tt = static_cast<int>(row % t);
for (int e = threadIdx.x; e < c * f; e += 256) {
const int fb = e / c, ci = e % c;
Y[row * c * f + e] = X[((n * f + fb) * t + tt) * c + ci];
}
}
3 changes: 3 additions & 0 deletions zig/kernels/cuda/prefill_attention.cu
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,9 @@ template __global__ void tf_prefill_attention::full_kernel<72, 8, 8>(const __nv_
// Head dim 80, eight warps, two blocks an SM (RADIO's tower, 16 heads of 80): full_kernel<80>'s bits, 1.35x faster.
template __global__ void tf_prefill_attention::vision_kernel<80, 8>(const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, int, int,
float);
// Head dim 64, eight warps (Qwen3-ASR's audio tower, 14 or 16 heads of 64 over a window of its rows).
template __global__ void tf_prefill_attention::vision_kernel<64, 8>(const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, int, int,
float);
// Head dim 128, eight warps (MOSS-Image's denoiser, 24 heads of 128 over its image and prompt rows).
template __global__ void tf_prefill_attention::vision_kernel<128, 8>(const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, int, int,
float);
Expand Down
31 changes: 30 additions & 1 deletion zig/kernels/cuda/vit.cu
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Vision towers' glue (cuda/vit.zig; LFM2-VL's SigLIP2, RADIO): LayerNorm, Linear epilogues, activations, unshuffle.
// Vision and audio towers' glue (cuda/vit.zig): LayerNorm, Linear epilogues, activations, unshuffle, conv taps.

#include <cuda_bf16.h>
#include <math.h>
Expand Down Expand Up @@ -91,6 +91,35 @@ extern "C" __global__ void __launch_bounds__(NT) tf_vit_unshuffle(const __nv_bfl
}
}

// Block (row (n, fo, to), columns): 3x3 stride-2 pad-1 taps of X [n][fi][ti][c], column ci 9 + kh 3 + kw; 0 past 9 c.
extern "C" __global__ void __launch_bounds__(NT) tf_vit_conv_cols(const __nv_bfloat16* __restrict__ X, __nv_bfloat16* __restrict__ Y, int fi,
int ti, int c, int ld) {
const int fo = (fi - 1) / 2 + 1, to = (ti - 1) / 2 + 1;
const int64_t r = blockIdx.x;
const int64_t n = r / (static_cast<int64_t>(fo) * to);
const int f = static_cast<int>(r / to % fo), t = static_cast<int>(r % to);
const int j = blockIdx.y * NT + threadIdx.x;
if (j >= ld) return;
__nv_bfloat16 v = __float2bfloat16_rn(0.0f);
if (j < 9 * c) {
const int ci = j / 9, kh = j % 9 / 3, kw = j % 3;
const int sf = 2 * f - 1 + kh, st = 2 * t - 1 + kw;
if (sf >= 0 && st >= 0 && sf < fi && st < ti) v = X[((n * fi + sf) * ti + st) * c + ci];
}
Y[r * ld + j] = v;
}

// Block a row (n, t): Y [n][t][c * f + fb] = X [n][fb][t][c], a conv's channels-last rows as torch flattens [c][f].
extern "C" __global__ void __launch_bounds__(NT) tf_vit_conv_flatten(const __nv_bfloat16* __restrict__ X, __nv_bfloat16* __restrict__ Y, int f,
int t, int c) {
const int64_t row = blockIdx.x, n = row / t;
const int tt = static_cast<int>(row % t);
for (int e = threadIdx.x; e < c * f; e += NT) {
const int ci = e / f, fb = e % f;
Y[row * c * f + e] = X[((n * f + fb) * t + tt) * c + ci];
}
}

// Element i: bf16(x), round to nearest even (a picture's float patches for the tower's first Linear).
extern "C" __global__ void __launch_bounds__(NT) tf_vit_cast(const float* __restrict__ X, __nv_bfloat16* __restrict__ Y, int64_t count) {
const int64_t at = static_cast<int64_t>(blockIdx.x) * NT + threadIdx.x;
Expand Down
Loading
Loading