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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import contextlib
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Dict, List, Tuple, Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.distributed as dist
|
| 8 |
+
import sys
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
import torch.utils.checkpoint as checkpoint
|
| 12 |
+
|
| 13 |
+
from .torch_utils import cpu_autocast
|
| 14 |
+
|
| 15 |
+
from .optimization import configure_optimizer
|
| 16 |
+
from .compression import decompress_bits
|
| 17 |
+
from .parity import enforce_parity
|
| 18 |
+
|
| 19 |
+
_mask_cache: Dict[Tuple[int, torch.device], torch.Tensor] = {}
|
| 20 |
+
_attention_cache: Dict[str, torch.Tensor] = {} # For caching attention patterns
|
| 21 |
+
_MAX_CACHE_SIZE = 50 # Limit cache growth
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def clear_cache():
|
| 25 |
+
"""Clear memory caches to prevent OOM in long sequences."""
|
| 26 |
+
global _mask_cache, _attention_cache
|
| 27 |
+
_mask_cache.clear()
|
| 28 |
+
_attention_cache.clear()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def get_tri_mask(seq_len: int, device: torch.device) -> torch.Tensor:
|
| 32 |
+
"""Return or create a cached upper-triangular mask with memory management."""
|
| 33 |
+
key = (seq_len, device)
|
| 34 |
+
|
| 35 |
+
# Clear cache if it gets too large
|
| 36 |
+
if len(_mask_cache) > _MAX_CACHE_SIZE:
|
| 37 |
+
clear_cache()
|
| 38 |
+
|
| 39 |
+
if key not in _mask_cache:
|
| 40 |
+
_mask_cache[key] = torch.triu(
|
| 41 |
+
torch.ones(seq_len, seq_len, device=device, dtype=torch.bool), 1
|
| 42 |
+
)
|
| 43 |
+
return _mask_cache[key]
|
| 44 |
+
|
| 45 |
+
try: # torch.compile may not work on all Python versions
|
| 46 |
+
if torch.__version__ and tuple(map(int, torch.__version__.split(".")[:2])) >= (2, 0) and sys.version_info < (3, 11):
|
| 47 |
+
compile_fn = torch.compile
|
| 48 |
+
else:
|
| 49 |
+
raise RuntimeError
|
| 50 |
+
except Exception: # pragma: no cover - handle missing torch or unsupported version
|
| 51 |
+
|
| 52 |
+
def compile_fn(fn=None, **kwargs):
|
| 53 |
+
if fn is None:
|
| 54 |
+
return lambda f: f
|
| 55 |
+
return fn
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class PositionalEncoding(nn.Module):
|
| 59 |
+
"""Sinusoidal positional encoding."""
|
| 60 |
+
|
| 61 |
+
def __init__(self, d_model: int, max_len: int = 1024) -> None:
|
| 62 |
+
super().__init__()
|
| 63 |
+
pe = torch.zeros(max_len, d_model)
|
| 64 |
+
pos = torch.arange(0, max_len, dtype=torch.float32).unsqueeze(1)
|
| 65 |
+
inv = torch.exp(
|
| 66 |
+
torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model)
|
| 67 |
+
)
|
| 68 |
+
pe[:, 0::2] = torch.sin(pos * inv)
|
| 69 |
+
pe[:, 1::2] = torch.cos(pos * inv)
|
| 70 |
+
self.register_buffer("pe", pe.unsqueeze(1))
|
| 71 |
+
|
| 72 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 73 |
+
"""Add positional encoding to input tensor."""
|
| 74 |
+
return x + self.pe[: x.size(0)]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class LoggingTransformerEncoderLayer(nn.Module):
|
| 78 |
+
"""Transformer encoder layer that exposes attention weights.
|
| 79 |
+
|
| 80 |
+
It optionally performs chunked attention with a fixed window size.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
def __init__(
|
| 84 |
+
self,
|
| 85 |
+
d_model: int,
|
| 86 |
+
nhead: int,
|
| 87 |
+
dim_feedforward: int = 512,
|
| 88 |
+
dropout: float = 0.1,
|
| 89 |
+
chunk_size: Optional[int] = None,
|
| 90 |
+
overlap: int = 0,
|
| 91 |
+
full_attn_logging: Optional[bool] = None,
|
| 92 |
+
) -> None:
|
| 93 |
+
super().__init__()
|
| 94 |
+
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout, batch_first=True)
|
| 95 |
+
self.chunk_size = chunk_size
|
| 96 |
+
self.overlap = overlap
|
| 97 |
+
if full_attn_logging is None:
|
| 98 |
+
full_attn_logging = False if chunk_size is not None else True
|
| 99 |
+
self.full_attn_logging = full_attn_logging
|
| 100 |
+
self.linear1 = nn.Linear(d_model, dim_feedforward)
|
| 101 |
+
self.dropout = nn.Dropout(dropout)
|
| 102 |
+
self.linear2 = nn.Linear(dim_feedforward, d_model)
|
| 103 |
+
self.norm1 = nn.LayerNorm(d_model)
|
| 104 |
+
self.norm2 = nn.LayerNorm(d_model)
|
| 105 |
+
self.dropout1 = nn.Dropout(dropout)
|
| 106 |
+
self.dropout2 = nn.Dropout(dropout)
|
| 107 |
+
self.activation = F.relu
|
| 108 |
+
|
| 109 |
+
def _chunked_attn(
|
| 110 |
+
self, src: torch.Tensor, attn_mask: Optional[torch.Tensor] = None
|
| 111 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 112 |
+
"""Perform memory-efficient chunked self attention with overlap."""
|
| 113 |
+
T, B, D = src.shape
|
| 114 |
+
|
| 115 |
+
# Early return for small sequences
|
| 116 |
+
if T <= 128 or self.chunk_size is None or self.chunk_size >= T:
|
| 117 |
+
return self._full_attn(src, attn_mask)
|
| 118 |
+
|
| 119 |
+
src_b = src.transpose(0, 1) # [B, T, D]
|
| 120 |
+
C = self.chunk_size
|
| 121 |
+
O = self.overlap
|
| 122 |
+
n_chunks = (T + C - 1) // C
|
| 123 |
+
pad_len = n_chunks * C - T
|
| 124 |
+
|
| 125 |
+
# Process chunks with gradient checkpointing for memory efficiency
|
| 126 |
+
outputs = []
|
| 127 |
+
weights_list = []
|
| 128 |
+
|
| 129 |
+
# Use memory-efficient processing
|
| 130 |
+
with torch.cuda.amp.autocast(enabled=torch.cuda.is_available()):
|
| 131 |
+
for chunk_idx in range(n_chunks):
|
| 132 |
+
start_idx = chunk_idx * C
|
| 133 |
+
end_idx = min(start_idx + C + 2 * O, T + O)
|
| 134 |
+
|
| 135 |
+
# Extract chunk with overlap
|
| 136 |
+
chunk_start = max(0, start_idx - O)
|
| 137 |
+
chunk_end = min(T, end_idx)
|
| 138 |
+
chunk = src_b[:, chunk_start:chunk_end]
|
| 139 |
+
|
| 140 |
+
# Pad if necessary
|
| 141 |
+
if chunk.size(1) < C + 2 * O:
|
| 142 |
+
pad_size = C + 2 * O - chunk.size(1)
|
| 143 |
+
chunk = F.pad(chunk, (0, 0, 0, pad_size))
|
| 144 |
+
|
| 145 |
+
chunk_len = chunk.size(1)
|
| 146 |
+
mask = get_tri_mask(chunk_len, src.device) if attn_mask is not None else None
|
| 147 |
+
|
| 148 |
+
# Apply attention to chunk
|
| 149 |
+
out, weights = self.self_attn(
|
| 150 |
+
chunk, chunk, chunk,
|
| 151 |
+
attn_mask=mask,
|
| 152 |
+
need_weights=self.full_attn_logging,
|
| 153 |
+
average_attn_weights=False,
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
# Extract the core part (remove overlap)
|
| 157 |
+
core_start = O if chunk_idx > 0 else 0
|
| 158 |
+
core_end = core_start + min(C, T - start_idx)
|
| 159 |
+
outputs.append(out[:, core_start:core_end])
|
| 160 |
+
|
| 161 |
+
if self.full_attn_logging and weights is not None:
|
| 162 |
+
weights_list.append(weights[:, :, core_start:core_end])
|
| 163 |
+
|
| 164 |
+
# Clear intermediate tensors to save memory
|
| 165 |
+
del out, weights, chunk
|
| 166 |
+
if torch.cuda.is_available():
|
| 167 |
+
torch.cuda.empty_cache()
|
| 168 |
+
|
| 169 |
+
# Concatenate outputs
|
| 170 |
+
seq = torch.cat(outputs, dim=1)
|
| 171 |
+
|
| 172 |
+
# Handle attention weights
|
| 173 |
+
if self.full_attn_logging and weights_list:
|
| 174 |
+
# Use sparse representation for large sequences
|
| 175 |
+
if T > 1024:
|
| 176 |
+
attn_out = torch.empty(0, device=src.device) # Skip full attention for very long sequences
|
| 177 |
+
else:
|
| 178 |
+
attn_out = torch.cat(weights_list, dim=2)
|
| 179 |
+
else:
|
| 180 |
+
attn_out = torch.empty(0, device=src.device)
|
| 181 |
+
|
| 182 |
+
return seq.transpose(0, 1), attn_out
|
| 183 |
+
|
| 184 |
+
def _full_attn(self, src: torch.Tensor, attn_mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 185 |
+
"""Standard full attention for smaller sequences."""
|
| 186 |
+
qkv = src.transpose(0, 1)
|
| 187 |
+
attn_output, attn_weights = self.self_attn(
|
| 188 |
+
qkv, qkv, qkv,
|
| 189 |
+
attn_mask=attn_mask,
|
| 190 |
+
need_weights=True,
|
| 191 |
+
average_attn_weights=False,
|
| 192 |
+
)
|
| 193 |
+
return attn_output.transpose(0, 1), attn_weights
|
| 194 |
+
|
| 195 |
+
def forward(
|
| 196 |
+
self, src: torch.Tensor, attn_mask: Optional[torch.Tensor] = None
|
| 197 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 198 |
+
"""Return output and attention map."""
|
| 199 |
+
if self.chunk_size is not None:
|
| 200 |
+
attn_output, attn_weights = self._chunked_attn(src, attn_mask)
|
| 201 |
+
else:
|
| 202 |
+
qkv = src.transpose(0, 1)
|
| 203 |
+
attn_output, attn_weights = self.self_attn(
|
| 204 |
+
qkv,
|
| 205 |
+
qkv,
|
| 206 |
+
qkv,
|
| 207 |
+
attn_mask=attn_mask,
|
| 208 |
+
need_weights=True,
|
| 209 |
+
average_attn_weights=False,
|
| 210 |
+
)
|
| 211 |
+
attn_output = attn_output.transpose(0, 1)
|
| 212 |
+
src = src + self.dropout1(attn_output)
|
| 213 |
+
src = self.norm1(src)
|
| 214 |
+
out = self.linear2(self.dropout(self.activation(self.linear1(src))))
|
| 215 |
+
src = src + self.dropout2(out)
|
| 216 |
+
src = self.norm2(src)
|
| 217 |
+
return src, attn_weights.detach()
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class ReversibleLoggingTransformerEncoderLayer(nn.Module):
|
| 221 |
+
"""Reversible transformer encoder layer with checkpointing."""
|
| 222 |
+
|
| 223 |
+
def __init__(
|
| 224 |
+
self,
|
| 225 |
+
d_model: int,
|
| 226 |
+
nhead: int,
|
| 227 |
+
dim_feedforward: int = 512,
|
| 228 |
+
dropout: float = 0.1,
|
| 229 |
+
chunk_size: Optional[int] = None,
|
| 230 |
+
overlap: int = 0,
|
| 231 |
+
full_attn_logging: Optional[bool] = None,
|
| 232 |
+
) -> None:
|
| 233 |
+
super().__init__()
|
| 234 |
+
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout, batch_first=True)
|
| 235 |
+
self.chunk_size = chunk_size
|
| 236 |
+
self.overlap = overlap
|
| 237 |
+
if full_attn_logging is None:
|
| 238 |
+
full_attn_logging = False if chunk_size is not None else True
|
| 239 |
+
self.full_attn_logging = full_attn_logging
|
| 240 |
+
self.linear1 = nn.Linear(d_model, dim_feedforward)
|
| 241 |
+
self.dropout = nn.Dropout(dropout)
|
| 242 |
+
self.linear2 = nn.Linear(dim_feedforward, d_model)
|
| 243 |
+
self.norm1 = nn.LayerNorm(d_model)
|
| 244 |
+
self.norm2 = nn.LayerNorm(d_model)
|
| 245 |
+
self.dropout1 = nn.Dropout(dropout)
|
| 246 |
+
self.dropout2 = nn.Dropout(dropout)
|
| 247 |
+
self.activation = F.relu
|
| 248 |
+
|
| 249 |
+
@compile_fn
|
| 250 |
+
def _sa_block(
|
| 251 |
+
self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None
|
| 252 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 253 |
+
if self.chunk_size is not None:
|
| 254 |
+
T, B, D = x.shape
|
| 255 |
+
x_b = x.transpose(0, 1)
|
| 256 |
+
C = self.chunk_size or T
|
| 257 |
+
O = self.overlap
|
| 258 |
+
n_chunks = (T + C - 1) // C
|
| 259 |
+
pad_len = n_chunks * C - T
|
| 260 |
+
src_pad = F.pad(x_b, (0, 0, O, pad_len + O))
|
| 261 |
+
chunk_len = C + 2 * O
|
| 262 |
+
chunks = src_pad.unfold(1, chunk_len, C)
|
| 263 |
+
mask = get_tri_mask(chunk_len, x.device) if attn_mask is not None else None
|
| 264 |
+
out, weights = self.self_attn(
|
| 265 |
+
chunks.reshape(B * n_chunks, chunk_len, D),
|
| 266 |
+
chunks.reshape(B * n_chunks, chunk_len, D),
|
| 267 |
+
chunks.reshape(B * n_chunks, chunk_len, D),
|
| 268 |
+
attn_mask=mask,
|
| 269 |
+
need_weights=True,
|
| 270 |
+
average_attn_weights=False,
|
| 271 |
+
)
|
| 272 |
+
out = out.view(B, n_chunks, chunk_len, D)[:, :, O : O + C]
|
| 273 |
+
weights = weights.view(B, n_chunks, self.self_attn.num_heads, chunk_len, chunk_len)[
|
| 274 |
+
:, :, :, O : O + C
|
| 275 |
+
]
|
| 276 |
+
seq = out.reshape(B, n_chunks * C, D)[:, :T]
|
| 277 |
+
if self.full_attn_logging and C < T:
|
| 278 |
+
full_attn = torch.zeros(
|
| 279 |
+
B, self.self_attn.num_heads, n_chunks * C, n_chunks * C, device=x.device
|
| 280 |
+
)
|
| 281 |
+
for idx in range(n_chunks):
|
| 282 |
+
s = idx * C
|
| 283 |
+
start = max(s - O, 0)
|
| 284 |
+
end = min(s + C, n_chunks * C)
|
| 285 |
+
src_start = O - (s - start)
|
| 286 |
+
src_end = src_start + (end - start)
|
| 287 |
+
full_attn[:, :, s : s + C, start:end] = weights[
|
| 288 |
+
:, idx, :, src_start:src_end
|
| 289 |
+
]
|
| 290 |
+
full_attn = full_attn[:, :, :T, :T]
|
| 291 |
+
weights = full_attn.detach()
|
| 292 |
+
else:
|
| 293 |
+
weights = torch.empty(0, device=x.device)
|
| 294 |
+
attn_out = seq.transpose(0, 1)
|
| 295 |
+
else:
|
| 296 |
+
qkv = x.transpose(0, 1)
|
| 297 |
+
attn_out, weights = self.self_attn(
|
| 298 |
+
qkv,
|
| 299 |
+
qkv,
|
| 300 |
+
qkv,
|
| 301 |
+
attn_mask=attn_mask,
|
| 302 |
+
need_weights=True,
|
| 303 |
+
average_attn_weights=False,
|
| 304 |
+
)
|
| 305 |
+
attn_out = attn_out.transpose(0, 1)
|
| 306 |
+
x = self.norm1(x + self.dropout1(attn_out))
|
| 307 |
+
return x, weights.detach()
|
| 308 |
+
|
| 309 |
+
@compile_fn
|
| 310 |
+
def _ff_block(self, x: torch.Tensor) -> torch.Tensor:
|
| 311 |
+
out = self.linear2(self.dropout(self.activation(self.linear1(x))))
|
| 312 |
+
x = self.norm2(x + self.dropout2(out))
|
| 313 |
+
return x
|
| 314 |
+
|
| 315 |
+
def forward(
|
| 316 |
+
self,
|
| 317 |
+
x1: torch.Tensor,
|
| 318 |
+
x2: torch.Tensor,
|
| 319 |
+
attn_mask: Optional[torch.Tensor] = None,
|
| 320 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 321 |
+
y1, weights = self._sa_block(x2, attn_mask)
|
| 322 |
+
y1 = x1 + y1
|
| 323 |
+
y2 = x2 + self._ff_block(y1)
|
| 324 |
+
return y1, y2, weights
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
class BitTransformerLM(nn.Module):
|
| 328 |
+
"""Transformer language model that operates on raw bits (0/1) with telemetry."""
|
| 329 |
+
|
| 330 |
+
def __init__(
|
| 331 |
+
self,
|
| 332 |
+
d_model: int = 128,
|
| 333 |
+
nhead: int = 8,
|
| 334 |
+
num_layers: int = 4,
|
| 335 |
+
dim_feedforward: int = 512,
|
| 336 |
+
max_seq_len: int = 1024,
|
| 337 |
+
lambda_K: float = 1.0,
|
| 338 |
+
lambda_C: float = 1.0,
|
| 339 |
+
lambda_S: float = 1.0,
|
| 340 |
+
reversible: bool = False,
|
| 341 |
+
use_checkpoint: bool = True,
|
| 342 |
+
use_autocast: bool = False,
|
| 343 |
+
use_act: bool = False,
|
| 344 |
+
act_threshold: float = 0.9,
|
| 345 |
+
chunk_size: Optional[int] = None,
|
| 346 |
+
overlap: int = 0,
|
| 347 |
+
full_attn_logging: Optional[bool] = None,
|
| 348 |
+
) -> None:
|
| 349 |
+
"""Create a BitTransformer language model.
|
| 350 |
+
|
| 351 |
+
Args:
|
| 352 |
+
full_attn_logging: When ``False`` and ``chunk_size`` is
|
| 353 |
+
smaller than the sequence length, the model skips
|
| 354 |
+
reconstructing the full ``T×T`` attention matrices for
|
| 355 |
+
telemetry to reduce memory use.
|
| 356 |
+
"""
|
| 357 |
+
super().__init__()
|
| 358 |
+
self.d_model = d_model
|
| 359 |
+
self.num_layers = num_layers
|
| 360 |
+
self.lambda_K = lambda_K
|
| 361 |
+
self.lambda_C = lambda_C
|
| 362 |
+
self.lambda_S = lambda_S
|
| 363 |
+
self.reversible = reversible
|
| 364 |
+
self.use_checkpoint = use_checkpoint
|
| 365 |
+
self.use_autocast = use_autocast
|
| 366 |
+
self.use_act = use_act
|
| 367 |
+
self.act_threshold = act_threshold
|
| 368 |
+
self.chunk_size = chunk_size
|
| 369 |
+
self.overlap = overlap
|
| 370 |
+
if full_attn_logging is None:
|
| 371 |
+
full_attn_logging = False if chunk_size is not None else True
|
| 372 |
+
self.full_attn_logging = full_attn_logging
|
| 373 |
+
|
| 374 |
+
# Bit embedding: two possible input values
|
| 375 |
+
self.embedding = nn.Embedding(2, d_model)
|
| 376 |
+
self.pos_enc = PositionalEncoding(d_model, max_len=max_seq_len)
|
| 377 |
+
|
| 378 |
+
layer_cls = (
|
| 379 |
+
ReversibleLoggingTransformerEncoderLayer
|
| 380 |
+
if reversible
|
| 381 |
+
else LoggingTransformerEncoderLayer
|
| 382 |
+
)
|
| 383 |
+
self.layers = nn.ModuleList(
|
| 384 |
+
[
|
| 385 |
+
layer_cls(
|
| 386 |
+
d_model=d_model,
|
| 387 |
+
nhead=nhead,
|
| 388 |
+
dim_feedforward=dim_feedforward,
|
| 389 |
+
chunk_size=chunk_size,
|
| 390 |
+
overlap=overlap,
|
| 391 |
+
full_attn_logging=full_attn_logging,
|
| 392 |
+
)
|
| 393 |
+
for _ in range(num_layers)
|
| 394 |
+
]
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
if self.use_act:
|
| 398 |
+
self.halt_projs = nn.ModuleList(
|
| 399 |
+
[nn.Linear(d_model, 1) for _ in range(num_layers)]
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
self.out_head = nn.Linear(d_model, 2) # output logits for bit=0 or bit=1
|
| 403 |
+
|
| 404 |
+
def expand_positional_encoding(self, new_len: int) -> None:
|
| 405 |
+
"""Expand positional encoding to at least ``new_len``."""
|
| 406 |
+
cur_len = self.pos_enc.pe.size(0)
|
| 407 |
+
if new_len <= cur_len:
|
| 408 |
+
return
|
| 409 |
+
device = self.pos_enc.pe.device
|
| 410 |
+
d_model = self.d_model
|
| 411 |
+
pe = torch.zeros(new_len, d_model, device=device)
|
| 412 |
+
pe[:cur_len] = self.pos_enc.pe.squeeze(1)
|
| 413 |
+
pos = torch.arange(cur_len, new_len, dtype=torch.float32, device=device).unsqueeze(1)
|
| 414 |
+
inv = torch.exp(torch.arange(0, d_model, 2, device=device).float() * -(math.log(10000.0) / d_model))
|
| 415 |
+
pe[cur_len:, 0::2] = torch.sin(pos * inv)
|
| 416 |
+
pe[cur_len:, 1::2] = torch.cos(pos * inv)
|
| 417 |
+
self.pos_enc.pe = pe.unsqueeze(1)
|
| 418 |
+
|
| 419 |
+
def set_lambdas(self, lambda_K: float, lambda_C: float, lambda_S: float) -> None:
|
| 420 |
+
"""Update weighting coefficients for telemetry metrics."""
|
| 421 |
+
self.lambda_K = lambda_K
|
| 422 |
+
self.lambda_C = lambda_C
|
| 423 |
+
self.lambda_S = lambda_S
|
| 424 |
+
|
| 425 |
+
def _maybe_decompress(self, codes: torch.Tensor) -> torch.Tensor:
|
| 426 |
+
"""Return raw bit sequences, decompressing if input appears run-length encoded."""
|
| 427 |
+
if codes.dim() <= 1:
|
| 428 |
+
return codes
|
| 429 |
+
needs_decompress = codes.max().item() > 1
|
| 430 |
+
if not needs_decompress and codes.size(1) % 2 == 0:
|
| 431 |
+
vals = codes[:, 0::2]
|
| 432 |
+
if torch.all(vals[:, 1:] != vals[:, :-1]):
|
| 433 |
+
needs_decompress = True
|
| 434 |
+
if not needs_decompress:
|
| 435 |
+
return codes
|
| 436 |
+
seqs = [decompress_bits(row.to(torch.uint8)) for row in codes]
|
| 437 |
+
max_len = max(seq.numel() for seq in seqs)
|
| 438 |
+
padded = [F.pad(seq, (0, max_len - seq.numel())) for seq in seqs]
|
| 439 |
+
return torch.stack(padded)
|
| 440 |
+
|
| 441 |
+
def negentropy_kpi(self, codes: torch.Tensor) -> torch.Tensor:
|
| 442 |
+
"""Approximate negentropy of bit sequences.
|
| 443 |
+
|
| 444 |
+
Returns a value in ``[0, 1]`` where ``1`` denotes a perfectly ordered
|
| 445 |
+
sequence (all zeros or ones) and ``0`` reflects maximal entropy.
|
| 446 |
+
"""
|
| 447 |
+
codes = self._maybe_decompress(codes)
|
| 448 |
+
p = codes.float().mean(dim=1)
|
| 449 |
+
entropy = -(p * torch.log(p + 1e-9) + (1 - p) * torch.log(1 - p + 1e-9))
|
| 450 |
+
max_e = math.log(2.0)
|
| 451 |
+
return 1 - entropy / max_e
|
| 452 |
+
|
| 453 |
+
def lz_complexity(self, codes: torch.Tensor) -> torch.Tensor:
|
| 454 |
+
"""Differentiable proxy for Lempel–Ziv complexity.
|
| 455 |
+
|
| 456 |
+
Values near ``0`` indicate highly compressible sequences while values
|
| 457 |
+
approaching ``1`` correspond to rapid bit alternation.
|
| 458 |
+
"""
|
| 459 |
+
codes = self._maybe_decompress(codes)
|
| 460 |
+
diffs = torch.abs(codes[:, 1:] - codes[:, :-1])
|
| 461 |
+
return diffs.float().mean(dim=1)
|
| 462 |
+
|
| 463 |
+
def negentropy_logits(self, logits: torch.Tensor, detach: bool = True) -> torch.Tensor:
|
| 464 |
+
"""Negentropy computed from model logits.
|
| 465 |
+
|
| 466 |
+
Parameters
|
| 467 |
+
----------
|
| 468 |
+
logits: ``torch.Tensor``
|
| 469 |
+
Logit tensor of shape ``(B, T, 2)``.
|
| 470 |
+
detach: bool, default ``True``
|
| 471 |
+
When ``True`` the computation is detached from the autograd graph.
|
| 472 |
+
"""
|
| 473 |
+
assert logits.dim() == 3 and logits.size(-1) == 2, "logits must be [B,T,2]"
|
| 474 |
+
prob = logits.softmax(-1)
|
| 475 |
+
if detach:
|
| 476 |
+
prob = prob.detach()
|
| 477 |
+
p = prob[..., 1].mean(dim=1)
|
| 478 |
+
entropy = -(p * torch.log(p + 1e-9) + (1 - p) * torch.log(1 - p + 1e-9))
|
| 479 |
+
max_e = math.log(2.0)
|
| 480 |
+
return 1 - entropy / max_e
|
| 481 |
+
|
| 482 |
+
def lz_complexity_logits(self, logits: torch.Tensor, detach: bool = True) -> torch.Tensor:
|
| 483 |
+
"""LZ complexity proxy computed from logits.
|
| 484 |
+
|
| 485 |
+
Parameters
|
| 486 |
+
----------
|
| 487 |
+
logits: ``torch.Tensor``
|
| 488 |
+
Logit tensor of shape ``(B, T, 2)``.
|
| 489 |
+
detach: bool, default ``True``
|
| 490 |
+
When ``True`` the computation is detached from the autograd graph.
|
| 491 |
+
"""
|
| 492 |
+
assert logits.dim() == 3 and logits.size(-1) == 2, "logits must be [B,T,2]"
|
| 493 |
+
prob = logits.softmax(-1)
|
| 494 |
+
if detach:
|
| 495 |
+
prob = prob.detach()
|
| 496 |
+
prob1 = prob[..., 1]
|
| 497 |
+
diffs = torch.abs(prob1[:, 1:] - prob1[:, :-1])
|
| 498 |
+
return diffs.mean(dim=1)
|
| 499 |
+
|
| 500 |
+
def symbiosis_kl_logits(
|
| 501 |
+
self, logits: torch.Tensor, ref_prob: float = 0.5, detach: bool = True
|
| 502 |
+
) -> torch.Tensor:
|
| 503 |
+
"""Symbiosis score from KL divergence to a reference distribution.
|
| 504 |
+
|
| 505 |
+
Returns a value in ``[0, 1]`` with ``1`` meaning perfect agreement with
|
| 506 |
+
the reference distribution and ``0`` indicating maximal divergence.
|
| 507 |
+
"""
|
| 508 |
+
assert logits.dim() == 3 and logits.size(-1) == 2, "logits must be [B,T,2]"
|
| 509 |
+
probs = logits.softmax(-1)
|
| 510 |
+
if detach:
|
| 511 |
+
probs = probs.detach()
|
| 512 |
+
ref = torch.tensor([1 - ref_prob, ref_prob], device=logits.device)
|
| 513 |
+
kl = (probs * (probs.clamp_min(1e-9).log() - ref.log())).sum(-1).mean(dim=1)
|
| 514 |
+
max_kl = math.log(2.0)
|
| 515 |
+
return 1 - kl / max_kl
|
| 516 |
+
|
| 517 |
+
def _act_step(
|
| 518 |
+
self,
|
| 519 |
+
hidden: torch.Tensor,
|
| 520 |
+
idx: int,
|
| 521 |
+
halt_prob: torch.Tensor,
|
| 522 |
+
act_state: torch.Tensor,
|
| 523 |
+
halt_history: List[torch.Tensor],
|
| 524 |
+
) -> Tuple[torch.Tensor, torch.Tensor, bool]:
|
| 525 |
+
"""Apply one step of ACT halting logic."""
|
| 526 |
+
p = torch.sigmoid(self.halt_projs[idx](hidden))
|
| 527 |
+
delta = (1 - halt_prob) * p
|
| 528 |
+
halt_prob = halt_prob + delta
|
| 529 |
+
act_state = act_state + hidden * delta
|
| 530 |
+
halt_history.append(halt_prob.detach())
|
| 531 |
+
min_prob = halt_prob.detach().min()
|
| 532 |
+
if dist.is_initialized():
|
| 533 |
+
dist.all_reduce(min_prob, op=dist.ReduceOp.MIN)
|
| 534 |
+
return halt_prob, act_state, min_prob.item() >= self.act_threshold
|
| 535 |
+
|
| 536 |
+
def forward(
|
| 537 |
+
self, bit_seq: torch.Tensor, causal: bool = True
|
| 538 |
+
) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
|
| 539 |
+
"""Forward pass returning logits and telemetry from the same graph.
|
| 540 |
+
|
| 541 |
+
By default the model uses causal masking and (optional) chunked
|
| 542 |
+
attention. When ``causal`` is ``False`` the model operates in
|
| 543 |
+
"Diffusion LM" mode. In this mode chunked attention is temporarily
|
| 544 |
+
disabled so that every token can attend to the full sequence
|
| 545 |
+
bidirectionally. The original chunking configuration is restored after
|
| 546 |
+
the forward pass.
|
| 547 |
+
"""
|
| 548 |
+
|
| 549 |
+
# Disable chunking when running in bidirectional (non-causal) mode
|
| 550 |
+
orig_chunks = None
|
| 551 |
+
orig_model_chunk = None
|
| 552 |
+
if not causal and self.chunk_size is not None:
|
| 553 |
+
orig_model_chunk = self.chunk_size
|
| 554 |
+
orig_chunks = [layer.chunk_size for layer in self.layers]
|
| 555 |
+
self.chunk_size = None
|
| 556 |
+
for layer in self.layers:
|
| 557 |
+
layer.chunk_size = None
|
| 558 |
+
|
| 559 |
+
try:
|
| 560 |
+
ctx = cpu_autocast() if self.use_autocast else contextlib.nullcontext()
|
| 561 |
+
with ctx:
|
| 562 |
+
x = self.embedding(bit_seq).transpose(0, 1) * math.sqrt(self.d_model)
|
| 563 |
+
x = self.pos_enc(x)
|
| 564 |
+
|
| 565 |
+
attn_mask = get_tri_mask(x.size(0), x.device) if causal else None
|
| 566 |
+
|
| 567 |
+
activations: List[torch.Tensor] = []
|
| 568 |
+
attn_maps: List[torch.Tensor] = []
|
| 569 |
+
halt_history: List[torch.Tensor] = []
|
| 570 |
+
if self.use_act:
|
| 571 |
+
halt_prob = torch.zeros(x.size(0), x.size(1), 1, device=x.device)
|
| 572 |
+
act_state = torch.zeros_like(x)
|
| 573 |
+
if self.reversible:
|
| 574 |
+
x1, x2 = x, x
|
| 575 |
+
for idx, layer in enumerate(self.layers):
|
| 576 |
+
if self.use_checkpoint:
|
| 577 |
+
x1, x2, attn = checkpoint.checkpoint(
|
| 578 |
+
layer, x1, x2, attn_mask
|
| 579 |
+
)
|
| 580 |
+
else:
|
| 581 |
+
x1, x2, attn = layer(x1, x2, attn_mask)
|
| 582 |
+
combined = (x1 + x2) / 2
|
| 583 |
+
activations.append(combined)
|
| 584 |
+
if attn.numel() > 0:
|
| 585 |
+
attn_maps.append(attn)
|
| 586 |
+
if self.use_act:
|
| 587 |
+
halt_prob, act_state, should_break = self._act_step(
|
| 588 |
+
combined, idx, halt_prob, act_state, halt_history
|
| 589 |
+
)
|
| 590 |
+
if should_break:
|
| 591 |
+
break
|
| 592 |
+
x = (x1 + x2) / 2
|
| 593 |
+
else:
|
| 594 |
+
for idx, layer in enumerate(self.layers):
|
| 595 |
+
if self.use_checkpoint:
|
| 596 |
+
x, attn = checkpoint.checkpoint(layer, x, attn_mask)
|
| 597 |
+
else:
|
| 598 |
+
x, attn = layer(x, attn_mask)
|
| 599 |
+
activations.append(x)
|
| 600 |
+
if attn.numel() > 0:
|
| 601 |
+
attn_maps.append(attn)
|
| 602 |
+
if self.use_act:
|
| 603 |
+
halt_prob, act_state, should_break = self._act_step(
|
| 604 |
+
x, idx, halt_prob, act_state, halt_history
|
| 605 |
+
)
|
| 606 |
+
if should_break:
|
| 607 |
+
break
|
| 608 |
+
if self.use_act:
|
| 609 |
+
act_state = act_state + x * (1 - halt_prob)
|
| 610 |
+
x = act_state
|
| 611 |
+
logits = self.out_head(x)
|
| 612 |
+
|
| 613 |
+
# Per-layer entropy of activations
|
| 614 |
+
entropies = []
|
| 615 |
+
for act in activations:
|
| 616 |
+
prob = act.softmax(-1)
|
| 617 |
+
ent = -(prob * prob.clamp_min(1e-9).log()).sum(-1).mean()
|
| 618 |
+
entropies.append(ent)
|
| 619 |
+
|
| 620 |
+
attn_entropies = []
|
| 621 |
+
for attn in attn_maps:
|
| 622 |
+
prob = attn # weights are already softmaxed
|
| 623 |
+
ent = -(prob * prob.clamp_min(1e-9).log()).sum(-1)
|
| 624 |
+
ent = ent.mean(1)
|
| 625 |
+
attn_entropies.append(ent)
|
| 626 |
+
if attn_entropies:
|
| 627 |
+
attn_entropy_map = torch.stack(attn_entropies).mean(0)
|
| 628 |
+
else:
|
| 629 |
+
attn_entropy_map = torch.zeros(
|
| 630 |
+
bit_seq.size(0), bit_seq.size(1), device=bit_seq.device
|
| 631 |
+
)
|
| 632 |
+
max_ent = math.log(attn_entropy_map.size(-1))
|
| 633 |
+
attn_entropy_map = attn_entropy_map / max_ent
|
| 634 |
+
attn_entropy = attn_entropy_map.mean(1)
|
| 635 |
+
|
| 636 |
+
logits_bt = logits.transpose(0, 1)
|
| 637 |
+
negentropy_in = self.negentropy_kpi(bit_seq)
|
| 638 |
+
lz_in = self.lz_complexity(bit_seq.float())
|
| 639 |
+
negentropy_logits_b = self.negentropy_logits(logits_bt, detach=False)
|
| 640 |
+
lz_logits_b = self.lz_complexity_logits(logits_bt, detach=False)
|
| 641 |
+
kl_div_b = self.symbiosis_kl_logits(logits_bt, detach=False)
|
| 642 |
+
|
| 643 |
+
raw_sym = (
|
| 644 |
+
(self.lambda_K * negentropy_logits_b + self.lambda_C * lz_logits_b) / 2
|
| 645 |
+
+ negentropy_logits_b * lz_logits_b
|
| 646 |
+
- self.lambda_S * kl_div_b
|
| 647 |
+
- 0.1 * attn_entropy
|
| 648 |
+
)
|
| 649 |
+
weight_norm = torch.stack([p.norm() for p in self.parameters()]).mean().detach()
|
| 650 |
+
raw_sym = raw_sym - 0.01 * weight_norm
|
| 651 |
+
sym_score = torch.sigmoid(raw_sym)
|
| 652 |
+
|
| 653 |
+
B, T = bit_seq.shape
|
| 654 |
+
assert logits_bt.shape[:2] == (B, T)
|
| 655 |
+
assert attn_entropy_map.shape == (B, T)
|
| 656 |
+
|
| 657 |
+
telemetry = {
|
| 658 |
+
"activations": activations,
|
| 659 |
+
"attention_maps": attn_maps,
|
| 660 |
+
"attention_entropy": attn_entropy_map,
|
| 661 |
+
"entropy": entropies,
|
| 662 |
+
"attention_entropy_mean": attn_entropy,
|
| 663 |
+
"negentropy_input": negentropy_in.detach(),
|
| 664 |
+
"lz_complexity_input": lz_in.detach(),
|
| 665 |
+
"negentropy_logits": negentropy_logits_b.detach(),
|
| 666 |
+
"lz_complexity_logits": lz_logits_b.detach(),
|
| 667 |
+
"symbiosis_kl": kl_div_b.detach(),
|
| 668 |
+
"symbiosis_score": sym_score.detach(),
|
| 669 |
+
}
|
| 670 |
+
if self.use_act:
|
| 671 |
+
telemetry["halt_probs"] = halt_history
|
| 672 |
+
|
| 673 |
+
return logits_bt, telemetry
|
| 674 |
+
finally:
|
| 675 |
+
if orig_chunks is not None:
|
| 676 |
+
self.chunk_size = orig_model_chunk
|
| 677 |
+
for layer, chunk in zip(self.layers, orig_chunks):
|
| 678 |
+
layer.chunk_size = chunk
|
| 679 |
+
|
| 680 |
+
def forward_compressed(
|
| 681 |
+
self, compressed_bits, causal: bool = True
|
| 682 |
+
) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
|
| 683 |
+
"""Decompress bit sequences then run the normal forward pass."""
|
| 684 |
+
if isinstance(compressed_bits, torch.Tensor) and compressed_bits.dim() == 1:
|
| 685 |
+
sequences = [decompress_bits(compressed_bits).to(torch.long)]
|
| 686 |
+
else:
|
| 687 |
+
sequences = [decompress_bits(c).to(torch.long) for c in compressed_bits]
|
| 688 |
+
lengths = [seq.numel() for seq in sequences]
|
| 689 |
+
if len(set(lengths)) != 1:
|
| 690 |
+
raise ValueError("Sequences decompress to different lengths")
|
| 691 |
+
bits = torch.stack(sequences)
|
| 692 |
+
return self.forward(bits, causal=causal)
|
| 693 |
+
|
| 694 |
+
def _current_params(self) -> Dict:
|
| 695 |
+
"""Return a dictionary with the current model hyperparameters."""
|
| 696 |
+
return {
|
| 697 |
+
"d_model": self.d_model,
|
| 698 |
+
"nhead": self.layers[0].self_attn.num_heads,
|
| 699 |
+
"num_layers": self.num_layers,
|
| 700 |
+
"dim_feedforward": self.layers[0].linear1.out_features,
|
| 701 |
+
"max_seq_len": self.pos_enc.pe.size(0),
|
| 702 |
+
"lambda_K": self.lambda_K,
|
| 703 |
+
"lambda_C": self.lambda_C,
|
| 704 |
+
"lambda_S": self.lambda_S,
|
| 705 |
+
"reversible": self.reversible,
|
| 706 |
+
"use_checkpoint": self.use_checkpoint,
|
| 707 |
+
"use_autocast": self.use_autocast,
|
| 708 |
+
"use_act": self.use_act,
|
| 709 |
+
"act_threshold": self.act_threshold,
|
| 710 |
+
"chunk_size": self.chunk_size,
|
| 711 |
+
"overlap": self.overlap,
|
| 712 |
+
}
|
| 713 |
+
|
| 714 |
+
def double_width(self) -> "BitTransformerLM":
|
| 715 |
+
"""Return a copy of the model with doubled hidden size."""
|
| 716 |
+
from .scale import expand_model
|
| 717 |
+
|
| 718 |
+
params = self._current_params()
|
| 719 |
+
params["d_model"] *= 2
|
| 720 |
+
params["dim_feedforward"] *= 2
|
| 721 |
+
return expand_model(self, params)
|
| 722 |
+
|
| 723 |
+
def double_layers(self) -> "BitTransformerLM":
|
| 724 |
+
"""Return a copy of the model with twice as many layers."""
|
| 725 |
+
from .scale import expand_model
|
| 726 |
+
|
| 727 |
+
params = self._current_params()
|
| 728 |
+
params["num_layers"] *= 2
|
| 729 |
+
return expand_model(self, params)
|
| 730 |
+
|
| 731 |
+
def double_length(self) -> "BitTransformerLM":
|
| 732 |
+
"""Return a copy of the model with doubled maximum sequence length."""
|
| 733 |
+
from .scale import expand_model
|
| 734 |
+
|
| 735 |
+
params = self._current_params()
|
| 736 |
+
params["max_seq_len"] *= 2
|
| 737 |
+
params["chunk_size"] = params["max_seq_len"]
|
| 738 |
+
return expand_model(self, params)
|
| 739 |
+
|
| 740 |
+
def train_full_sequence(
|
| 741 |
+
self,
|
| 742 |
+
bits: torch.Tensor,
|
| 743 |
+
*,
|
| 744 |
+
ctx_bits: int = 4096,
|
| 745 |
+
detach_every_n: int = 1_048_576,
|
| 746 |
+
) -> float:
|
| 747 |
+
"""Train on a long bit tensor using sliding windows.
|
| 748 |
+
|
| 749 |
+
Parameters
|
| 750 |
+
----------
|
| 751 |
+
bits: ``torch.Tensor``
|
| 752 |
+
1D tensor containing the full bit sequence.
|
| 753 |
+
ctx_bits: int
|
| 754 |
+
Size of the training context window.
|
| 755 |
+
detach_every_n: int
|
| 756 |
+
Interval in bits for optimizer updates and graph detachment.
|
| 757 |
+
Returns
|
| 758 |
+
-------
|
| 759 |
+
float
|
| 760 |
+
Mean loss over all windows.
|
| 761 |
+
"""
|
| 762 |
+
self.train()
|
| 763 |
+
optimizer, scheduler = configure_optimizer(
|
| 764 |
+
self, lr=1e-3, total_steps=max(1, bits.numel() // ctx_bits)
|
| 765 |
+
)
|
| 766 |
+
accum = 0
|
| 767 |
+
total_loss = 0.0
|
| 768 |
+
count = 0
|
| 769 |
+
for start in range(0, bits.numel() - ctx_bits - 1, ctx_bits):
|
| 770 |
+
segment = bits[start : start + ctx_bits + 1].unsqueeze(0)
|
| 771 |
+
logits, _ = self(segment)
|
| 772 |
+
pred = logits[:, :-1, :].reshape(-1, 2)
|
| 773 |
+
target = segment[:, 1:].reshape(-1)
|
| 774 |
+
loss = F.cross_entropy(pred, target)
|
| 775 |
+
loss.backward()
|
| 776 |
+
accum += ctx_bits
|
| 777 |
+
total_loss += loss.item()
|
| 778 |
+
count += 1
|
| 779 |
+
if accum >= detach_every_n:
|
| 780 |
+
torch.nn.utils.clip_grad_norm_(self.parameters(), 1.0)
|
| 781 |
+
optimizer.step()
|
| 782 |
+
scheduler.step()
|
| 783 |
+
optimizer.zero_grad()
|
| 784 |
+
accum = 0
|
| 785 |
+
if accum > 0:
|
| 786 |
+
torch.nn.utils.clip_grad_norm_(self.parameters(), 1.0)
|
| 787 |
+
optimizer.step()
|
| 788 |
+
scheduler.step()
|
| 789 |
+
optimizer.zero_grad()
|
| 790 |
+
return total_loss / max(1, count)
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
def infer_long_sequence(
|
| 794 |
+
model: BitTransformerLM,
|
| 795 |
+
bits: torch.Tensor,
|
| 796 |
+
*,
|
| 797 |
+
ctx_bits: int = 4096,
|
| 798 |
+
overlap: int = 256,
|
| 799 |
+
) -> Tuple[torch.Tensor, List[Dict[str, torch.Tensor]]]:
|
| 800 |
+
"""Infer a long bit sequence using sliding windows with overlap."""
|
| 801 |
+
model.eval()
|
| 802 |
+
device = next(model.parameters()).device
|
| 803 |
+
bits = bits.to(device)
|
| 804 |
+
step = ctx_bits - overlap
|
| 805 |
+
outputs: List[torch.Tensor] = []
|
| 806 |
+
logs: List[Dict[str, torch.Tensor]] = []
|
| 807 |
+
for start in range(0, bits.numel(), step):
|
| 808 |
+
window = bits[start : start + ctx_bits].unsqueeze(0)
|
| 809 |
+
logits, tele = model(window, causal=True)
|
| 810 |
+
pred = logits.argmax(-1).squeeze(0)
|
| 811 |
+
outputs.append(pred)
|
| 812 |
+
logs.append(tele)
|
| 813 |
+
out = torch.cat(outputs)[: bits.numel()]
|
| 814 |
+
return out, logs
|
| 815 |
+
|
| 816 |
+
|
| 817 |
+
def diffusion_inference(
|
| 818 |
+
model: BitTransformerLM,
|
| 819 |
+
*,
|
| 820 |
+
length: int,
|
| 821 |
+
steps: int = 8,
|
| 822 |
+
batch_size: int = 1,
|
| 823 |
+
init_bits: Optional[torch.Tensor] = None,
|
| 824 |
+
schedule: str = "linear",
|
| 825 |
+
) -> torch.Tensor:
|
| 826 |
+
"""Generate bit sequences using iterative denoising diffusion.
|
| 827 |
+
|
| 828 |
+
Parameters
|
| 829 |
+
----------
|
| 830 |
+
model: ``BitTransformerLM``
|
| 831 |
+
The model used for denoising. It is run in non-causal mode with
|
| 832 |
+
chunked attention disabled, enabling full-context bidirectional
|
| 833 |
+
attention.
|
| 834 |
+
length: int
|
| 835 |
+
Length of the bit sequences to generate.
|
| 836 |
+
steps: int, default ``8``
|
| 837 |
+
Number of denoising iterations. More steps generally yield sharper
|
| 838 |
+
samples at the cost of compute.
|
| 839 |
+
batch_size: int, default ``1``
|
| 840 |
+
Number of sequences to generate in parallel.
|
| 841 |
+
init_bits: ``torch.Tensor`` | ``None``
|
| 842 |
+
Optional initial noisy bits of shape ``(batch_size, length)``. When
|
| 843 |
+
``None`` random noise is used.
|
| 844 |
+
schedule: str, default ``"linear"``
|
| 845 |
+
Noise schedule for the denoising mask probability. Options are
|
| 846 |
+
``"linear"``, ``"cosine"``, and ``"exp"``.
|
| 847 |
+
|
| 848 |
+
Returns
|
| 849 |
+
-------
|
| 850 |
+
``torch.Tensor``
|
| 851 |
+
A tensor of shape ``(batch_size, length)`` containing generated bits.
|
| 852 |
+
"""
|
| 853 |
+
|
| 854 |
+
model.eval()
|
| 855 |
+
device = next(model.parameters()).device
|
| 856 |
+
if init_bits is None:
|
| 857 |
+
bits = torch.randint(0, 2, (batch_size, length), device=device)
|
| 858 |
+
else:
|
| 859 |
+
bits = init_bits.to(device)
|
| 860 |
+
if bits.shape != (batch_size, length):
|
| 861 |
+
raise ValueError("init_bits must have shape (batch_size, length)")
|
| 862 |
+
|
| 863 |
+
for step in range(steps):
|
| 864 |
+
logits, _ = model(bits, causal=False)
|
| 865 |
+
prob = logits.softmax(-1)[..., 1]
|
| 866 |
+
t = (step + 1) / steps
|
| 867 |
+
if schedule == "linear":
|
| 868 |
+
mask_prob = 1.0 - t
|
| 869 |
+
elif schedule == "cosine":
|
| 870 |
+
mask_prob = math.cos(math.pi * t / 2)
|
| 871 |
+
elif schedule == "exp":
|
| 872 |
+
mask_prob = math.exp(-5 * t)
|
| 873 |
+
else:
|
| 874 |
+
raise ValueError(f"unknown schedule: {schedule}")
|
| 875 |
+
mask = (torch.rand_like(bits.float()) < mask_prob).long()
|
| 876 |
+
sampled = torch.bernoulli(prob).long()
|
| 877 |
+
bits = torch.where(mask.bool(), sampled, bits)
|
| 878 |
+
if bits.shape[-1] % 9 == 0:
|
| 879 |
+
bits, corrections = enforce_parity(bits)
|
| 880 |
+
if corrections:
|
| 881 |
+
logging.info("Parity corrections applied: %d", corrections)
|
| 882 |
+
try:
|
| 883 |
+
from .safety import hil_safe_inference
|
| 884 |
+
|
| 885 |
+
hil_safe_inference(model, bits, causal=False, strict=False)
|
| 886 |
+
except RuntimeError as exc:
|
| 887 |
+
logging.warning("Safety gate warning: %s", exc)
|
| 888 |
+
return bits
|
| 889 |
+
|
| 890 |
+
|
| 891 |
+
def example_usage() -> float:
|
| 892 |
+
"""Run the example from the README and return the loss."""
|
| 893 |
+
B, L = 4, 16
|
| 894 |
+
model = BitTransformerLM(
|
| 895 |
+
d_model=64, nhead=4, num_layers=2, dim_feedforward=256, max_seq_len=L
|
| 896 |
+
)
|
| 897 |
+
bits = torch.randint(0, 2, (B, L), dtype=torch.long)
|
| 898 |
+
logits, _ = model(bits)
|
| 899 |
+
pred = logits[:, :-1, :].reshape(-1, 2)
|
| 900 |
+
target = bits[:, 1:].reshape(-1)
|
| 901 |
+
loss = F.cross_entropy(pred, target)
|
| 902 |
+
return loss.item()
|
| 903 |
+
|
| 904 |
+
|
| 905 |
+
def example_training_step() -> Tuple[float, Dict[str, torch.Tensor]]:
|
| 906 |
+
"""Demonstrate a training step where metrics do not affect gradients."""
|
| 907 |
+
B, L = 4, 16
|
| 908 |
+
model = BitTransformerLM(
|
| 909 |
+
d_model=32, nhead=4, num_layers=1, dim_feedforward=64, max_seq_len=L
|
| 910 |
+
)
|
| 911 |
+
optimizer, scheduler = configure_optimizer(model, lr=1e-3, total_steps=1)
|
| 912 |
+
|
| 913 |
+
bits = torch.randint(0, 2, (B, L), dtype=torch.long)
|
| 914 |
+
logits, telemetry = model(bits)
|
| 915 |
+
|
| 916 |
+
pred = logits[:, :-1, :].reshape(-1, 2)
|
| 917 |
+
target = bits[:, 1:].reshape(-1)
|
| 918 |
+
loss = F.cross_entropy(pred, target)
|
| 919 |
+
|
| 920 |
+
loss.backward()
|
| 921 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 922 |
+
optimizer.step()
|
| 923 |
+
scheduler.step()
|
| 924 |
+
optimizer.zero_grad()
|
| 925 |
+
return loss.item(), telemetry
|
| 926 |
+
|
| 927 |
+
|
| 928 |
+
if __name__ == "__main__":
|
| 929 |
+
loss, telemetry = example_training_step()
|
| 930 |
+
print("Composite loss:", loss)
|
| 931 |
+
print("Telemetry keys:", list(telemetry.keys()))
|