Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 4 additions & 0 deletions aspec/config/train_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,10 @@ class TrainingConfig:
# Full-vocabulary KL intermediates are processed in bounded token chunks.
jetspec_distillation_temperature: float = 1.0
jetspec_kl_chunk_rows: int = 256
# Bounds the retained BF16 teacher logits; 0 disables retention and None
# keeps the model default. This is a memory/speed knob, not objective state,
# so it stays out of the exact-recovery topology.
jetspec_teacher_logits_budget_bytes: Optional[int] = None
# Main JetSpec results use uniform per-position weights (gamma = 0).
jetspec_loss_decay_gamma: float = 0.0
# Pack multiple complete documents into one fixed row. The controller owns
Expand Down
208 changes: 180 additions & 28 deletions aspec/models/jetspec.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,51 @@
import torch.nn.functional as F

from aspec.models.dflash import DFlashModel
from aspec.models.ops.jetspec_kl import (
_backward_from_logits,
_forward_from_logits,
use_fused_jetspec_kl,
)

_MIN_TEMPERATURE = 1e-6
_MAX_TEMPERATURE = math.sqrt(torch.finfo(torch.float32).max)
# Bound the retained teacher logits: 1920 active rows x 151936 vocabulary at
# BF16 is about 0.58 GB, while much longer selections fall back to recompute.
TEACHER_LOGITS_BUDGET_BYTES = 4 * 1024**3


def _projection_dtype(hidden, weight=None):
"""Dtype ``F.linear`` produces for the teacher projection.

Autocast never narrows float64, so a float64 operand keeps the projection
in float64 regardless of the autocast dtype. Without autocast the result is
the usual dtype promotion of the two operands.
"""
if hidden.dtype == torch.float64 or (
weight is not None and weight.dtype == torch.float64
):
return torch.float64
device_type = hidden.device.type
if torch.is_autocast_enabled(device_type):
return torch.get_autocast_dtype(device_type)
if weight is None:
return hidden.dtype
return torch.promote_types(hidden.dtype, weight.dtype)


def should_retain_teacher_logits(rows, vocab, dtype,
budget_bytes=TEACHER_LOGITS_BUDGET_BYTES):
if isinstance(rows, bool) or isinstance(vocab, bool):
raise ValueError("teacher-logit retention needs integer row/vocabulary counts")
rows, vocab = int(rows), int(vocab)
if rows < 0 or vocab < 1:
raise ValueError("teacher-logit retention needs rows >= 0 and vocab >= 1")
if not isinstance(dtype, torch.dtype) or not dtype.is_floating_point:
raise ValueError("teacher-logit retention needs a floating-point dtype")
if budget_bytes <= 0:
return False
element_size = torch.finfo(dtype).bits // 8
return rows > 0 and rows * vocab * element_size <= budget_bytes


class _ChunkedForwardKL(torch.autograd.Function):
Expand All @@ -25,34 +67,97 @@ class _ChunkedForwardKL(torch.autograd.Function):
Saving ``log_q``/``log_p`` per chunk would keep O(tokens * vocabulary) FP32
state alive until backward. The custom backward instead retains the existing
Draft logits and teacher hidden states, then recomputes one chunk at a time.

``retain_teacher`` stores the BF16 teacher logits within the caller's budget
so backward can skip the frozen teacher projection. ``fused`` replaces the
FP32 ``log_softmax``/``kl_div`` chunks with the tiled Triton epilogue.
"""

@staticmethod
def forward(ctx, draft_logits, hidden, lm_head_weight, temperature, chunk_rows, active):
def forward(ctx, draft_logits, hidden, lm_head_weight, temperature, chunk_rows,
active, retain_teacher, fused):
device_type = hidden.device.type
ctx.autocast_enabled = torch.is_autocast_enabled(device_type)
ctx.autocast_dtype = torch.get_autocast_dtype(device_type)
rows = draft_logits.shape[0]
vocabulary = draft_logits.shape[1]
projected_dtype = _projection_dtype(hidden, lm_head_weight)
if fused:
if not draft_logits.is_cuda:
raise ValueError("fused JetSpec KL requires CUDA logits")
if draft_logits.dtype != torch.bfloat16 or projected_dtype != torch.bfloat16:
raise ValueError("fused JetSpec KL requires BF16 draft/teacher logits")
if not draft_logits.is_contiguous():
raise ValueError("fused JetSpec KL requires contiguous draft logits")
kl = torch.zeros(rows, dtype=torch.float32, device=draft_logits.device)
for start in range(0, active.numel(), chunk_rows):
row_ids = active[start : start + chunk_rows]
target_logits = F.linear(
hidden.index_select(0, row_ids), lm_head_weight
).float()
log_p = F.log_softmax(target_logits / temperature, dim=-1)
log_q = F.log_softmax(
draft_logits.index_select(0, row_ids).float() / temperature, dim=-1
teacher_buffer = None
if retain_teacher:
teacher_buffer = torch.empty(
(active.numel(), vocabulary), dtype=projected_dtype,
device=draft_logits.device,
)
chunk = F.kl_div(log_q, log_p, reduction="none", log_target=True).sum(-1)
kl.index_put_((row_ids,), chunk * (temperature * temperature))
ctx.save_for_backward(draft_logits, hidden, lm_head_weight, active)
norms = None
if fused:
norms = torch.empty((active.numel(), 4), dtype=torch.float32,
device=draft_logits.device)
# Autocast leaves FP64 (and other non-narrowed) projections at their
# input dtype, so the direct-buffer GEMM only serves projections that
# already have the buffer dtype; everything else keeps the reference
# projection and copies the result in.
direct_projection = (
teacher_buffer is not None
and hidden.dtype == projected_dtype
and lm_head_weight.dtype == projected_dtype
)
for start in range(0, active.numel(), chunk_rows):
row_ids = active[start:start + chunk_rows]
stop = start + row_ids.numel()
chunk_hidden = hidden.index_select(0, row_ids)
if direct_projection:
# Write the projection straight into the retained buffer: no
# chunk-sized temporary and no extra device-to-device copy.
target_logits = teacher_buffer[start:stop]
torch.mm(chunk_hidden, lm_head_weight.t(), out=target_logits)
else:
target_logits = F.linear(chunk_hidden, lm_head_weight)
if teacher_buffer is not None:
teacher_buffer[start:stop] = target_logits
draft_chunk = draft_logits.index_select(0, row_ids)
if fused:
chunk, chunk_norms = _forward_from_logits(
draft_chunk, target_logits, temperature
)
norms[start:stop] = chunk_norms
kl.index_put_((row_ids,), chunk)
else:
log_p = F.log_softmax(target_logits.float() / temperature, dim=-1)
log_q = F.log_softmax(draft_chunk.float() / temperature, dim=-1)
chunk = F.kl_div(log_q, log_p, reduction="none", log_target=True).sum(-1)
kl.index_put_((row_ids,), chunk * (temperature * temperature))
saved = [draft_logits, hidden, lm_head_weight, active]
if teacher_buffer is not None:
saved.append(teacher_buffer)
if norms is not None:
saved.append(norms)
ctx.save_for_backward(*saved)
ctx.temperature = temperature
ctx.chunk_rows = chunk_rows
ctx.retain_teacher = retain_teacher
ctx.fused = fused
return kl

@staticmethod
def backward(ctx, grad_kl):
draft_logits, hidden, lm_head_weight, active = ctx.saved_tensors
saved = ctx.saved_tensors
draft_logits, hidden, lm_head_weight, active = saved[:4]
cursor = 4
teacher_buffer = None
if ctx.retain_teacher:
teacher_buffer = saved[cursor]
cursor += 1
norms = None
if ctx.fused:
norms = saved[cursor]
temperature = ctx.temperature
gradient = torch.zeros_like(draft_logits)
with torch.autocast(
Expand All @@ -61,26 +166,41 @@ def backward(ctx, grad_kl):
enabled=ctx.autocast_enabled,
):
for start in range(0, active.numel(), ctx.chunk_rows):
row_ids = active[start : start + ctx.chunk_rows]
target_logits = F.linear(
hidden.index_select(0, row_ids), lm_head_weight
).float()
p = F.softmax(target_logits / temperature, dim=-1)
q = F.softmax(
draft_logits.index_select(0, row_ids).float() / temperature,
dim=-1,
)
scale = grad_kl.index_select(0, row_ids).float().unsqueeze(-1)
gradient.index_put_(
(row_ids,), ((q - p) * temperature * scale).to(gradient.dtype)
)
return gradient, None, None, None, None, None
row_ids = active[start:start + ctx.chunk_rows]
stop = start + row_ids.numel()
if teacher_buffer is not None:
target_logits = teacher_buffer[start:stop]
else:
target_logits = F.linear(
hidden.index_select(0, row_ids), lm_head_weight
)
draft_chunk = draft_logits.index_select(0, row_ids)
scale = grad_kl.index_select(0, row_ids).float()
if ctx.fused:
gradient.index_put_(
(row_ids,),
_backward_from_logits(
draft_chunk, target_logits, norms[start:stop],
scale, temperature,
),
)
else:
p = F.softmax(target_logits.float() / temperature, dim=-1)
q = F.softmax(draft_chunk.float() / temperature, dim=-1)
gradient.index_put_(
(row_ids,),
((q - p) * temperature * scale.unsqueeze(-1)).to(
gradient.dtype
),
)
return gradient, None, None, None, None, None, None, None


class JetSpecModel(DFlashModel):
"""DFlash block head with causal intra-block attention and forward KL."""

def __init__(self, *args, distillation_temperature=1.0, kl_chunk_rows=256, **kwargs):
def __init__(self, *args, distillation_temperature=1.0, kl_chunk_rows=256,
teacher_logits_budget_bytes=TEACHER_LOGITS_BUDGET_BYTES, **kwargs):
# Main JetSpec results use uniform per-position weights (gamma = 0).
kwargs.setdefault("loss_decay_gamma", 0.0)
super().__init__(*args, **kwargs)
Expand Down Expand Up @@ -112,6 +232,15 @@ def __init__(self, *args, distillation_temperature=1.0, kl_chunk_rows=256, **kwa
or kl_chunk_rows < 1):
raise ValueError("JetSpec kl_chunk_rows must be a positive integer")
self.kl_chunk_rows = int(kl_chunk_rows)
if (isinstance(teacher_logits_budget_bytes, bool)
or not isinstance(teacher_logits_budget_bytes, int)
or teacher_logits_budget_bytes < 0):
raise ValueError(
"JetSpec teacher_logits_budget_bytes must be a non-negative "
"integer; 0 disables teacher-logit retention"
)
self.teacher_logits_budget_bytes = int(teacher_logits_budget_bytes)
self.last_kl_path = None
if config is not None and hasattr(config, "block_size"):
if int(config.block_size) != self.block_size:
raise ValueError("JetSpec training block_size must match its Draft config")
Expand Down Expand Up @@ -170,13 +299,36 @@ def _training_loss(
)
# The custom backward recomputes one chunk at a time, so neither the
# forward nor the saved state keeps every full-vocabulary chunk alive.
# Retaining BF16 teacher logits within the budget skips the backward
# teacher projection; the tiled epilogue replaces the FP32 softmax/KL.
projected_dtype = _projection_dtype(flat_hidden, lm_head_weight)
# Held-out evaluation runs this forward under no_grad, where a retained
# teacher buffer would never be read by a backward.
retain_teacher = (
torch.is_grad_enabled()
and draft_logits.requires_grad
and should_retain_teacher_logits(
active.numel(), vocabulary, projected_dtype,
self.teacher_logits_budget_bytes,
)
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
fused = use_fused_jetspec_kl(
draft_logits, lm_head_weight, projected_dtype,
self.distillation_temperature,
)
self.last_kl_path = (
("tiled" if fused else "reference")
+ ("+retained" if retain_teacher else "+recompute")
)
kl = _ChunkedForwardKL.apply(
draft_logits,
flat_hidden,
lm_head_weight.detach(),
self.distillation_temperature,
self.kl_chunk_rows,
active,
retain_teacher,
fused,
)
return kl, kl, logits

Loading