Token Classification
lora
matthewagi's picture matt's picture
Initial model release
86599c0
Raw History Blame Contribute Delete
7.92 kB
from pathlib import Path
from types import SimpleNamespace
import importlib.util
import json
import torch
from torch import nn
from safetensors import safe_open
from transformers import AutoConfig
from transformers.models.qwen3_5_moe import modeling_qwen3_5_moe as hf
from vllm.forward_context import set_forward_context
from .packed import Layout, PackedRunner
class TokenWorker:
def initialize_detector(self, root, serving):
root, model_dir = Path(root), Path(serving)
spec = importlib.util.spec_from_file_location(
"detector_arch", root / "runtime/model.py"
)
arch = importlib.util.module_from_spec(spec)
spec.loader.exec_module(arch)
model = self.model_runner.model
model.pooler.initializing = False
runner = PackedRunner(model)
cfg = AutoConfig.from_pretrained(model_dir)
index = json.loads((model_dir / "model.safetensors.index.json").read_text())[
"weight_map"
]
with safe_open(root / "trainable.safetensors", framework="pt") as handle:
checkpoint = {
k: handle.get_tensor(k)
for k in handle.keys()
if k.startswith(("donor.", "head.", "attention_pool."))
}
def norm():
return hf.Qwen3_5MoeRMSNorm(cfg.hidden_size, cfg.rms_norm_eps)
def load_base(module, prefix):
state = {}
for k in module.state_dict():
full = "model." + prefix + k
with safe_open(model_dir / index[full], framework="pt") as f:
state[k] = f.get_tensor(full)
module.load_state_dict(state)
return module.bfloat16().cuda()
path = arch.AttributionPath()
path.rotary = hf.apply_rotary_pos_emb
path.backbone = nn.Module()
path.backbone.config = cfg
path.configure_attribution(0, 64)
path.attention_pool = arch.ChunkAttentionPool(cfg.hidden_size)
path.attention_pool.score.weight.data.copy_(
checkpoint["attention_pool.score.weight"]
)
path.attention_pool.cuda()
path.head.load_state_dict(
{k[5:]: v for k, v in checkpoint.items() if k.startswith("head.")}
)
path.head.cuda()
path.donor = nn.Module()
path.donor.self_attn = hf.Qwen3_5MoeAttention(cfg, 23).float()
path.donor.input_layernorm = norm().float()
path.donor.load_state_dict(
{k[6:]: v for k, v in checkpoint.items() if k.startswith("donor.")}
)
path.donor.cuda()
path.backbone.rotary_emb = hf.Qwen3_5MoeTextRotaryEmbedding(cfg).cuda()
path.backbone.norm = load_base(norm(), "norm.")
decoder = []
for i, block in enumerate(runner.backbone.layers[20:], 20):
layer = SimpleNamespace(block_type=block.layer_type, packed=block)
if block.layer_type == "full_attention":
layer.self_attn = load_base(
hf.Qwen3_5MoeAttention(cfg, i), f"layers.{i}.self_attn."
)
layer.input_layernorm = load_base(
norm(), f"layers.{i}.input_layernorm."
)
layer.post_attention_layernorm = load_base(
norm(), f"layers.{i}.post_attention_layernorm."
)
def mlp(x, block=block):
return block.mlp(x.flatten(0, 1)).reshape_as(x)
layer.mlp = mlp
decoder.append(layer)
path.backbone.layers = decoder
def linear(layer, x, rope, recompute_block):
h, res = layer.packed(
hidden_states=x.flatten(0, 1),
residual=None,
positions=runner.current_layout.positions,
)
return (h + res).reshape_as(x)
path.block = linear
path.eval()
make_layout = Layout.make
if getattr(cfg, "quantization_config", None):
if torch.cuda.get_device_capability() != (9, 0):
raise RuntimeError("The mixed-FP8 profile requires an SM90 Hopper GPU.")
from types import MethodType
from .hopper_gdn import forward as hopper_forward
from .hopper_options import (
packed_layout,
quantize_encoder,
set_fusion,
set_input_projection,
)
from .precision import convert, convert_dense_projections
convert(
runner.backbone,
self.vllm_config,
"fp8",
encoder_backend="deep_gemm",
encoder_layers=20,
)
encoder, tail = runner.backbone.layers[:20], runner.backbone.layers[20:]
quantize_encoder(encoder)
set_fusion(encoder, True)
set_input_projection(encoder, "shared")
roots = [tail, path.donor] + [
x.self_attn for x in decoder if x.block_type == "full_attention"
]
convert_dense_projections(roots, {id(block.mlp.gate) for block in tail})
for block in encoder:
if block.layer_type == "linear_attention":
block.linear_attn.forward = MethodType(
hopper_forward, block.linear_attn
)
for block in tail:
if block.layer_type == "linear_attention":
block.linear_attn._native_fp8_gates = True
make_layout = packed_layout
def forward(ids, lengths):
batch = len(lengths)
width = (max(lengths) + 63) // 64 * 64
packed = make_layout(lengths)
chunks = make_layout([width // 64] * batch)
positions = torch.arange(width, device="cuda").expand(batch, -1)
lengths = torch.tensor(lengths, device="cuda")
scatter = (
packed.cu[:-1, None] + positions.minimum(lengths[:, None] - 1)
).long()
runner.current_layout = packed
with set_forward_context(None, self.vllm_config, num_tokens=packed.total):
hidden = runner.backbone.embed_input_ids(ids.to("cuda"))
residual = None
for block in runner.backbone.layers[:20]:
hidden, residual = block(
hidden_states=hidden,
residual=residual,
positions=packed.positions,
)
encoded = hidden + residual
memory = encoded[scatter]
runner.current_layout = chunks
with set_forward_context(None, self.vllm_config, num_tokens=chunks.total):
context = path.decode(memory, positions, lengths)
row = torch.repeat_interleave(
torch.arange(batch, device="cuda"),
lengths,
output_size=packed.total,
)
chunk = packed.positions // 64
local = path.head.token(path.backbone.norm(encoded))
fused = local + path.head.context(context)[row, chunk]
out = path.head.out(torch.nn.functional.gelu(path.head.norm(fused)))
return out.float()
self.detector_forward = forward
@torch.inference_mode()
def score_detector(self, rows, copies):
lengths = [len(row) * copies for row in rows]
ids = torch.tensor(
[token for row in rows for token in row * copies], device="cuda"
)
with torch.autocast("cuda", dtype=torch.bfloat16):
full = self.detector_forward(ids, lengths)
return (
torch.cat(
[part[-len(row) :] for part, row in zip(full.split(lengths), rows)]
)
.cpu()
.numpy()
)