Instructions to use Synthyra/ANKH_base with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Synthyra/ANKH_base with Transformers:
# Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Synthyra/ANKH_base", trust_remote_code=True, dtype="auto") - Notebooks
- Google Colab
- Kaggle
Upload modeling_ankh.py with huggingface_hub
Browse files- modeling_ankh.py +538 -0
modeling_ankh.py
CHANGED
|
@@ -1150,6 +1150,544 @@ def bool_to_additive_mask(
|
|
| 1150 |
additive.masked_fill_(bool_mask.logical_not(), float("-inf"))
|
| 1151 |
return additive
|
| 1152 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1153 |
import math
|
| 1154 |
|
| 1155 |
import torch
|
|
|
|
| 1150 |
additive.masked_fill_(bool_mask.logical_not(), float("-inf"))
|
| 1151 |
return additive
|
| 1152 |
|
| 1153 |
+
import typing as T
|
| 1154 |
+
from dataclasses import dataclass, fields
|
| 1155 |
+
|
| 1156 |
+
import torch
|
| 1157 |
+
import torch.nn as nn
|
| 1158 |
+
import torch.nn.functional as F
|
| 1159 |
+
|
| 1160 |
+
|
| 1161 |
+
@dataclass
|
| 1162 |
+
class TTTConfig:
|
| 1163 |
+
lr: float = 4e-4
|
| 1164 |
+
steps: int = 30
|
| 1165 |
+
ags: int = 16
|
| 1166 |
+
batch_size: int = 2
|
| 1167 |
+
mask_ratio: float = 0.15
|
| 1168 |
+
crop_size: int = 1024
|
| 1169 |
+
bert_leave_prob: float = 0.1
|
| 1170 |
+
bert_replace_prob: float = 0.1
|
| 1171 |
+
optimizer: str = "sgd"
|
| 1172 |
+
momentum: float = 0.0
|
| 1173 |
+
weight_decay: float = 0.0
|
| 1174 |
+
seed: int | None = 0
|
| 1175 |
+
lora_rank: int = 8
|
| 1176 |
+
lora_alpha: float = 32.0
|
| 1177 |
+
lora_target_replace_module: str | None = None
|
| 1178 |
+
lora_target_modules: tuple[str, ...] | None = None
|
| 1179 |
+
initial_state_reset: bool = True
|
| 1180 |
+
automatic_best_state_reset: bool = False
|
| 1181 |
+
eval_each_step: bool = False
|
| 1182 |
+
gradient_clip: bool = False
|
| 1183 |
+
gradient_clip_max_norm: float = 1.0
|
| 1184 |
+
|
| 1185 |
+
@classmethod
|
| 1186 |
+
def from_kwargs(cls, **kwargs: T.Any) -> "TTTConfig":
|
| 1187 |
+
valid_names = {field.name for field in fields(cls)}
|
| 1188 |
+
unknown_names = set(kwargs) - valid_names
|
| 1189 |
+
assert len(unknown_names) == 0, f"Unknown TTTConfig fields: {sorted(unknown_names)}"
|
| 1190 |
+
return cls(**kwargs)
|
| 1191 |
+
|
| 1192 |
+
def merged(self, overrides: T.Mapping[str, T.Any] | "TTTConfig" | None) -> "TTTConfig":
|
| 1193 |
+
if overrides is None:
|
| 1194 |
+
return self
|
| 1195 |
+
if isinstance(overrides, TTTConfig):
|
| 1196 |
+
return overrides
|
| 1197 |
+
values = {field.name: self.__dict__[field.name] for field in fields(self)}
|
| 1198 |
+
for name, value in overrides.items():
|
| 1199 |
+
assert name in values, f"Unknown TTTConfig field: {name}"
|
| 1200 |
+
values[name] = value
|
| 1201 |
+
return TTTConfig(**values)
|
| 1202 |
+
|
| 1203 |
+
def verify(self) -> None:
|
| 1204 |
+
assert self.lr > 0.0, "TTT learning rate must be positive."
|
| 1205 |
+
assert self.steps >= 1, "TTT steps must be >= 1."
|
| 1206 |
+
assert self.ags >= 1, "TTT gradient accumulation steps must be >= 1."
|
| 1207 |
+
assert self.batch_size >= 1, "TTT batch_size must be >= 1."
|
| 1208 |
+
assert 0.0 < self.mask_ratio <= 1.0, "TTT mask_ratio must be in (0, 1]."
|
| 1209 |
+
assert self.crop_size >= 1, "TTT crop_size must be >= 1."
|
| 1210 |
+
assert self.lora_rank >= 1, "TTT v1 is LoRA-only, so lora_rank must be >= 1."
|
| 1211 |
+
assert self.lora_alpha > 0.0, "TTT lora_alpha must be positive."
|
| 1212 |
+
assert self.optimizer in {"adamw", "sgd"}, "TTT optimizer must be 'adamw' or 'sgd'."
|
| 1213 |
+
assert 0.0 <= self.bert_leave_prob <= 1.0, "bert_leave_prob must be in [0, 1]."
|
| 1214 |
+
assert 0.0 <= self.bert_replace_prob <= 1.0, "bert_replace_prob must be in [0, 1]."
|
| 1215 |
+
assert self.bert_leave_prob + self.bert_replace_prob <= 1.0, (
|
| 1216 |
+
"bert_leave_prob + bert_replace_prob must be <= 1."
|
| 1217 |
+
)
|
| 1218 |
+
if self.gradient_clip:
|
| 1219 |
+
assert self.gradient_clip_max_norm > 0.0, "gradient_clip_max_norm must be positive."
|
| 1220 |
+
|
| 1221 |
+
|
| 1222 |
+
class LoraInjectedLinear(nn.Module):
|
| 1223 |
+
def __init__(self, linear: nn.Module, rank: int, alpha: float) -> None:
|
| 1224 |
+
super().__init__()
|
| 1225 |
+
weight = linear._parameters["weight"]
|
| 1226 |
+
assert weight.ndim == 2, "LoRA can only wrap 2D linear weights."
|
| 1227 |
+
self.linear = linear
|
| 1228 |
+
self.linear.requires_grad_(False)
|
| 1229 |
+
self.rank = rank
|
| 1230 |
+
self.scale = alpha
|
| 1231 |
+
in_features = weight.shape[1]
|
| 1232 |
+
out_features = weight.shape[0]
|
| 1233 |
+
self.lora_down = nn.Linear(in_features, rank, bias=False, dtype=torch.float32)
|
| 1234 |
+
self.lora_up = nn.Linear(rank, out_features, bias=False, dtype=torch.float32)
|
| 1235 |
+
self.lora_down.to(device=weight.device)
|
| 1236 |
+
self.lora_up.to(device=weight.device)
|
| 1237 |
+
nn.init.normal_(self.lora_down.weight, std=1.0 / rank)
|
| 1238 |
+
nn.init.zeros_(self.lora_up.weight)
|
| 1239 |
+
|
| 1240 |
+
@property
|
| 1241 |
+
def weight(self) -> torch.Tensor:
|
| 1242 |
+
return self.linear._parameters["weight"]
|
| 1243 |
+
|
| 1244 |
+
@property
|
| 1245 |
+
def bias(self) -> torch.Tensor | None:
|
| 1246 |
+
return self.linear._parameters["bias"]
|
| 1247 |
+
|
| 1248 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 1249 |
+
base = self.linear(x)
|
| 1250 |
+
delta = self.lora_up(self.lora_down(x.to(dtype=torch.float32))) * self.scale
|
| 1251 |
+
return base + delta.to(dtype=base.dtype)
|
| 1252 |
+
|
| 1253 |
+
|
| 1254 |
+
class FastPLMTestTimeTrainingMixin:
|
| 1255 |
+
def init_ttt(self, ttt_config: TTTConfig | T.Mapping[str, T.Any] | None = None) -> None:
|
| 1256 |
+
base_config = TTTConfig()
|
| 1257 |
+
self._ttt_cfg = base_config.merged(ttt_config)
|
| 1258 |
+
self._ttt_cfg.verify()
|
| 1259 |
+
self._ttt_initialized = False
|
| 1260 |
+
self._ttt_initial_state: list[dict[str, torch.Tensor]] | None = None
|
| 1261 |
+
|
| 1262 |
+
@property
|
| 1263 |
+
def ttt_config(self) -> TTTConfig:
|
| 1264 |
+
if "_ttt_cfg" not in self.__dict__:
|
| 1265 |
+
self.init_ttt()
|
| 1266 |
+
return self._ttt_cfg
|
| 1267 |
+
|
| 1268 |
+
def _ttt_get_trainable_modules(self) -> list[nn.Module]:
|
| 1269 |
+
return [self]
|
| 1270 |
+
|
| 1271 |
+
def _ttt_get_frozen_modules(self) -> list[nn.Module]:
|
| 1272 |
+
return []
|
| 1273 |
+
|
| 1274 |
+
def _ttt_tokenize(
|
| 1275 |
+
self,
|
| 1276 |
+
seq: str | list[str] | None = None,
|
| 1277 |
+
input_ids: torch.Tensor | None = None,
|
| 1278 |
+
**kwargs: T.Any,
|
| 1279 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 1280 |
+
del kwargs
|
| 1281 |
+
if input_ids is not None:
|
| 1282 |
+
return input_ids
|
| 1283 |
+
assert seq is not None, "Pass either seq or input_ids for TTT."
|
| 1284 |
+
tokenized = self.tokenizer(seq, return_tensors="pt", padding=True)
|
| 1285 |
+
return tokenized["input_ids"]
|
| 1286 |
+
|
| 1287 |
+
def _ttt_mask_token(self) -> int:
|
| 1288 |
+
return int(self.tokenizer.mask_token_id)
|
| 1289 |
+
|
| 1290 |
+
def _ttt_padding_token(self) -> int:
|
| 1291 |
+
return int(self.tokenizer.pad_token_id)
|
| 1292 |
+
|
| 1293 |
+
def _ttt_replacement_tokens(self, input_ids: torch.Tensor) -> torch.Tensor:
|
| 1294 |
+
tokenizer = self.tokenizer
|
| 1295 |
+
special_ids = set(tokenizer.all_special_ids)
|
| 1296 |
+
vocab_size = int(self.config.vocab_size)
|
| 1297 |
+
ids = [idx for idx in range(vocab_size) if idx not in special_ids]
|
| 1298 |
+
assert len(ids) > 0, "TTT replacement token set is empty."
|
| 1299 |
+
return torch.tensor(ids, device=input_ids.device, dtype=input_ids.dtype)
|
| 1300 |
+
|
| 1301 |
+
def _ttt_predict_logits(
|
| 1302 |
+
self,
|
| 1303 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 1304 |
+
**kwargs: T.Any,
|
| 1305 |
+
) -> torch.Tensor:
|
| 1306 |
+
del kwargs
|
| 1307 |
+
if isinstance(batch, dict):
|
| 1308 |
+
output = self(**batch)
|
| 1309 |
+
return output.logits
|
| 1310 |
+
attention_mask = batch.ne(self._ttt_padding_token())
|
| 1311 |
+
output = self(input_ids=batch, attention_mask=attention_mask)
|
| 1312 |
+
return output.logits
|
| 1313 |
+
|
| 1314 |
+
def _ttt_eval_step(
|
| 1315 |
+
self,
|
| 1316 |
+
step: int,
|
| 1317 |
+
loss: float,
|
| 1318 |
+
seq: str | list[str] | None = None,
|
| 1319 |
+
input_ids: torch.Tensor | None = None,
|
| 1320 |
+
**kwargs: T.Any,
|
| 1321 |
+
) -> tuple[dict[str, T.Any], float | None]:
|
| 1322 |
+
del step, loss, seq, input_ids, kwargs
|
| 1323 |
+
return {}, None
|
| 1324 |
+
|
| 1325 |
+
def _ttt_is_lora_target(
|
| 1326 |
+
self,
|
| 1327 |
+
name: str,
|
| 1328 |
+
full_name: str,
|
| 1329 |
+
module: nn.Module,
|
| 1330 |
+
active: bool,
|
| 1331 |
+
target_modules: tuple[str, ...] | None,
|
| 1332 |
+
) -> bool:
|
| 1333 |
+
if not active:
|
| 1334 |
+
return False
|
| 1335 |
+
if isinstance(module, LoraInjectedLinear):
|
| 1336 |
+
return False
|
| 1337 |
+
if (
|
| 1338 |
+
target_modules is not None
|
| 1339 |
+
and name not in target_modules
|
| 1340 |
+
and full_name not in target_modules
|
| 1341 |
+
):
|
| 1342 |
+
return False
|
| 1343 |
+
if isinstance(module, nn.Linear):
|
| 1344 |
+
return True
|
| 1345 |
+
if "weight" not in module._parameters:
|
| 1346 |
+
return False
|
| 1347 |
+
weight = module._parameters["weight"]
|
| 1348 |
+
if weight is None or weight.ndim != 2:
|
| 1349 |
+
return False
|
| 1350 |
+
return "Linear" in module.__class__.__name__
|
| 1351 |
+
|
| 1352 |
+
def _ttt_inject_lora(self) -> int:
|
| 1353 |
+
cfg = self.ttt_config
|
| 1354 |
+
cfg.verify()
|
| 1355 |
+
target_class = cfg.lora_target_replace_module
|
| 1356 |
+
target_modules = cfg.lora_target_modules
|
| 1357 |
+
wrapped = 0
|
| 1358 |
+
|
| 1359 |
+
def inject(module: nn.Module, prefix: str, active: bool) -> None:
|
| 1360 |
+
nonlocal wrapped
|
| 1361 |
+
for name, child in list(module.named_children()):
|
| 1362 |
+
full_name = f"{prefix}.{name}" if prefix else name
|
| 1363 |
+
child_active = active
|
| 1364 |
+
if target_class is not None:
|
| 1365 |
+
child_active = active or child.__class__.__name__ == target_class
|
| 1366 |
+
if self._ttt_is_lora_target(name, full_name, child, child_active, target_modules):
|
| 1367 |
+
setattr(
|
| 1368 |
+
module,
|
| 1369 |
+
name,
|
| 1370 |
+
LoraInjectedLinear(child, rank=cfg.lora_rank, alpha=cfg.lora_alpha),
|
| 1371 |
+
)
|
| 1372 |
+
wrapped += 1
|
| 1373 |
+
continue
|
| 1374 |
+
inject(child, full_name, child_active)
|
| 1375 |
+
|
| 1376 |
+
for trainable_module in self._ttt_get_trainable_modules():
|
| 1377 |
+
inject(trainable_module, "", target_class is None)
|
| 1378 |
+
assert wrapped > 0, "TTT LoRA injection did not find any target modules."
|
| 1379 |
+
return wrapped
|
| 1380 |
+
|
| 1381 |
+
def _ttt_lora_modules(self) -> list[LoraInjectedLinear]:
|
| 1382 |
+
return [module for module in self.modules() if isinstance(module, LoraInjectedLinear)]
|
| 1383 |
+
|
| 1384 |
+
def _ttt_lora_parameters(self) -> list[nn.Parameter]:
|
| 1385 |
+
params: list[nn.Parameter] = []
|
| 1386 |
+
for module in self._ttt_lora_modules():
|
| 1387 |
+
params.extend(module.lora_down.parameters())
|
| 1388 |
+
params.extend(module.lora_up.parameters())
|
| 1389 |
+
assert len(params) > 0, "TTT has no LoRA parameters."
|
| 1390 |
+
return params
|
| 1391 |
+
|
| 1392 |
+
def _ttt_snapshot_lora_state(self) -> list[dict[str, torch.Tensor]]:
|
| 1393 |
+
snapshot = []
|
| 1394 |
+
for module in self._ttt_lora_modules():
|
| 1395 |
+
snapshot.append(
|
| 1396 |
+
{
|
| 1397 |
+
"lora_down.weight": module.lora_down.weight.detach().clone(),
|
| 1398 |
+
"lora_up.weight": module.lora_up.weight.detach().clone(),
|
| 1399 |
+
}
|
| 1400 |
+
)
|
| 1401 |
+
assert len(snapshot) > 0, "TTT has no LoRA state to snapshot."
|
| 1402 |
+
return snapshot
|
| 1403 |
+
|
| 1404 |
+
def _ttt_restore_lora_state(self, state: list[dict[str, torch.Tensor]]) -> None:
|
| 1405 |
+
modules = self._ttt_lora_modules()
|
| 1406 |
+
assert len(modules) == len(state), "TTT LoRA state/module count mismatch."
|
| 1407 |
+
with torch.no_grad():
|
| 1408 |
+
for module, module_state in zip(modules, state):
|
| 1409 |
+
module.lora_down.weight.copy_(module_state["lora_down.weight"])
|
| 1410 |
+
module.lora_up.weight.copy_(module_state["lora_up.weight"])
|
| 1411 |
+
|
| 1412 |
+
def _ttt_ensure_initialized(self) -> None:
|
| 1413 |
+
if "_ttt_cfg" not in self.__dict__:
|
| 1414 |
+
self.init_ttt()
|
| 1415 |
+
if self._ttt_initialized:
|
| 1416 |
+
return
|
| 1417 |
+
self._ttt_inject_lora()
|
| 1418 |
+
self._ttt_initial_state = self._ttt_snapshot_lora_state()
|
| 1419 |
+
self._ttt_initialized = True
|
| 1420 |
+
|
| 1421 |
+
def ttt_reset(self) -> None:
|
| 1422 |
+
self._ttt_ensure_initialized()
|
| 1423 |
+
assert self._ttt_initial_state is not None, "TTT initial state is not available."
|
| 1424 |
+
self._ttt_restore_lora_state(self._ttt_initial_state)
|
| 1425 |
+
|
| 1426 |
+
def _ttt_make_optimizer(self) -> torch.optim.Optimizer:
|
| 1427 |
+
cfg = self.ttt_config
|
| 1428 |
+
params = self._ttt_lora_parameters()
|
| 1429 |
+
if cfg.optimizer == "sgd":
|
| 1430 |
+
return torch.optim.SGD(
|
| 1431 |
+
params,
|
| 1432 |
+
lr=cfg.lr,
|
| 1433 |
+
momentum=cfg.momentum,
|
| 1434 |
+
weight_decay=cfg.weight_decay,
|
| 1435 |
+
)
|
| 1436 |
+
return torch.optim.AdamW(params, lr=cfg.lr, weight_decay=cfg.weight_decay)
|
| 1437 |
+
|
| 1438 |
+
def _ttt_to_device(
|
| 1439 |
+
self,
|
| 1440 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 1441 |
+
device: torch.device,
|
| 1442 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 1443 |
+
if isinstance(batch, dict):
|
| 1444 |
+
return {name: tensor.to(device) for name, tensor in batch.items()}
|
| 1445 |
+
return batch.to(device)
|
| 1446 |
+
|
| 1447 |
+
def _ttt_input_ids_from_batch(
|
| 1448 |
+
self,
|
| 1449 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 1450 |
+
) -> torch.Tensor:
|
| 1451 |
+
if isinstance(batch, dict):
|
| 1452 |
+
return batch["input_ids"]
|
| 1453 |
+
return batch
|
| 1454 |
+
|
| 1455 |
+
def _ttt_set_input_ids(
|
| 1456 |
+
self,
|
| 1457 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 1458 |
+
input_ids: torch.Tensor,
|
| 1459 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 1460 |
+
if isinstance(batch, dict):
|
| 1461 |
+
updated = dict(batch)
|
| 1462 |
+
updated["input_ids"] = input_ids
|
| 1463 |
+
return updated
|
| 1464 |
+
return input_ids
|
| 1465 |
+
|
| 1466 |
+
def _ttt_non_special_mask(self, input_ids: torch.Tensor) -> torch.Tensor:
|
| 1467 |
+
pad_token = self._ttt_padding_token()
|
| 1468 |
+
mask = input_ids.ne(pad_token)
|
| 1469 |
+
special_ids = set(self.tokenizer.all_special_ids)
|
| 1470 |
+
for special_id in special_ids:
|
| 1471 |
+
mask = mask & input_ids.ne(int(special_id))
|
| 1472 |
+
return mask
|
| 1473 |
+
|
| 1474 |
+
def _ttt_sample_crop(
|
| 1475 |
+
self,
|
| 1476 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 1477 |
+
generator: torch.Generator,
|
| 1478 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 1479 |
+
input_ids = self._ttt_input_ids_from_batch(batch)
|
| 1480 |
+
cfg = self.ttt_config
|
| 1481 |
+
if input_ids.shape[1] <= cfg.crop_size:
|
| 1482 |
+
return batch
|
| 1483 |
+
high = input_ids.shape[1] - cfg.crop_size + 1
|
| 1484 |
+
start = int(
|
| 1485 |
+
torch.randint(
|
| 1486 |
+
high,
|
| 1487 |
+
(1,),
|
| 1488 |
+
generator=generator,
|
| 1489 |
+
device=input_ids.device,
|
| 1490 |
+
).item()
|
| 1491 |
+
)
|
| 1492 |
+
end = start + cfg.crop_size
|
| 1493 |
+
if isinstance(batch, dict):
|
| 1494 |
+
cropped = {}
|
| 1495 |
+
for name, tensor in batch.items():
|
| 1496 |
+
if tensor.ndim >= 2 and tensor.shape[1] == input_ids.shape[1]:
|
| 1497 |
+
cropped[name] = tensor[:, start:end]
|
| 1498 |
+
else:
|
| 1499 |
+
cropped[name] = tensor
|
| 1500 |
+
return cropped
|
| 1501 |
+
return input_ids[:, start:end]
|
| 1502 |
+
|
| 1503 |
+
def _ttt_sample_batch(
|
| 1504 |
+
self,
|
| 1505 |
+
tokenized: torch.Tensor | dict[str, torch.Tensor],
|
| 1506 |
+
generator: torch.Generator,
|
| 1507 |
+
) -> tuple[torch.Tensor | dict[str, torch.Tensor], torch.Tensor]:
|
| 1508 |
+
cfg = self.ttt_config
|
| 1509 |
+
batch = self._ttt_sample_crop(tokenized, generator)
|
| 1510 |
+
input_ids = self._ttt_input_ids_from_batch(batch)
|
| 1511 |
+
rows = torch.randint(
|
| 1512 |
+
input_ids.shape[0],
|
| 1513 |
+
(cfg.batch_size,),
|
| 1514 |
+
generator=generator,
|
| 1515 |
+
device=input_ids.device,
|
| 1516 |
+
)
|
| 1517 |
+
if isinstance(batch, dict):
|
| 1518 |
+
sampled: torch.Tensor | dict[str, torch.Tensor] = {}
|
| 1519 |
+
for name, tensor in batch.items():
|
| 1520 |
+
if tensor.ndim >= 1 and tensor.shape[0] == input_ids.shape[0]:
|
| 1521 |
+
sampled[name] = tensor.index_select(0, rows)
|
| 1522 |
+
else:
|
| 1523 |
+
sampled[name] = tensor
|
| 1524 |
+
else:
|
| 1525 |
+
sampled = input_ids.index_select(0, rows)
|
| 1526 |
+
|
| 1527 |
+
sampled_ids = self._ttt_input_ids_from_batch(sampled)
|
| 1528 |
+
labels = sampled_ids.clone()
|
| 1529 |
+
non_special = self._ttt_non_special_mask(sampled_ids)
|
| 1530 |
+
label_mask = torch.zeros_like(non_special)
|
| 1531 |
+
for row_idx in range(sampled_ids.shape[0]):
|
| 1532 |
+
candidate_positions = torch.where(non_special[row_idx])[0]
|
| 1533 |
+
if candidate_positions.numel() == 0:
|
| 1534 |
+
continue
|
| 1535 |
+
num_mask = max(1, int(round(candidate_positions.numel() * cfg.mask_ratio)))
|
| 1536 |
+
order = torch.randperm(
|
| 1537 |
+
candidate_positions.numel(),
|
| 1538 |
+
generator=generator,
|
| 1539 |
+
device=sampled_ids.device,
|
| 1540 |
+
)
|
| 1541 |
+
chosen = candidate_positions[order[:num_mask]]
|
| 1542 |
+
label_mask[row_idx, chosen] = True
|
| 1543 |
+
labels = labels.masked_fill(~label_mask, -100)
|
| 1544 |
+
|
| 1545 |
+
masked_ids = sampled_ids.clone()
|
| 1546 |
+
chosen_positions = torch.where(label_mask)
|
| 1547 |
+
if chosen_positions[0].numel() > 0:
|
| 1548 |
+
random_values = torch.rand(
|
| 1549 |
+
chosen_positions[0].shape,
|
| 1550 |
+
generator=generator,
|
| 1551 |
+
device=sampled_ids.device,
|
| 1552 |
+
)
|
| 1553 |
+
leave = random_values < cfg.bert_leave_prob
|
| 1554 |
+
replace = (random_values >= cfg.bert_leave_prob) & (
|
| 1555 |
+
random_values < cfg.bert_leave_prob + cfg.bert_replace_prob
|
| 1556 |
+
)
|
| 1557 |
+
mask = ~(leave | replace)
|
| 1558 |
+
if mask.any():
|
| 1559 |
+
masked_ids[
|
| 1560 |
+
chosen_positions[0][mask],
|
| 1561 |
+
chosen_positions[1][mask],
|
| 1562 |
+
] = self._ttt_mask_token()
|
| 1563 |
+
if replace.any():
|
| 1564 |
+
replacement_tokens = self._ttt_replacement_tokens(sampled_ids)
|
| 1565 |
+
replacement_idx = torch.randint(
|
| 1566 |
+
replacement_tokens.shape[0],
|
| 1567 |
+
(int(replace.sum().item()),),
|
| 1568 |
+
generator=generator,
|
| 1569 |
+
device=sampled_ids.device,
|
| 1570 |
+
)
|
| 1571 |
+
masked_ids[
|
| 1572 |
+
chosen_positions[0][replace],
|
| 1573 |
+
chosen_positions[1][replace],
|
| 1574 |
+
] = replacement_tokens[replacement_idx]
|
| 1575 |
+
|
| 1576 |
+
return self._ttt_set_input_ids(sampled, masked_ids), labels
|
| 1577 |
+
|
| 1578 |
+
def ttt(
|
| 1579 |
+
self,
|
| 1580 |
+
seq: str | list[str] | None = None,
|
| 1581 |
+
input_ids: torch.Tensor | None = None,
|
| 1582 |
+
ttt_config: TTTConfig | T.Mapping[str, T.Any] | None = None,
|
| 1583 |
+
**kwargs: T.Any,
|
| 1584 |
+
) -> dict[str, T.Any]:
|
| 1585 |
+
if ttt_config is not None:
|
| 1586 |
+
if "_ttt_initialized" in self.__dict__ and self._ttt_initialized:
|
| 1587 |
+
next_cfg = self.ttt_config.merged(ttt_config)
|
| 1588 |
+
assert next_cfg.lora_rank == self.ttt_config.lora_rank, (
|
| 1589 |
+
"Changing lora_rank after TTT initialization is not supported."
|
| 1590 |
+
)
|
| 1591 |
+
assert next_cfg.lora_alpha == self.ttt_config.lora_alpha, (
|
| 1592 |
+
"Changing lora_alpha after TTT initialization is not supported."
|
| 1593 |
+
)
|
| 1594 |
+
assert (
|
| 1595 |
+
next_cfg.lora_target_replace_module
|
| 1596 |
+
== self.ttt_config.lora_target_replace_module
|
| 1597 |
+
), "Changing LoRA target class after TTT initialization is not supported."
|
| 1598 |
+
assert next_cfg.lora_target_modules == self.ttt_config.lora_target_modules, (
|
| 1599 |
+
"Changing LoRA target modules after TTT initialization is not supported."
|
| 1600 |
+
)
|
| 1601 |
+
self._ttt_cfg = next_cfg
|
| 1602 |
+
else:
|
| 1603 |
+
self.init_ttt(ttt_config)
|
| 1604 |
+
|
| 1605 |
+
self._ttt_ensure_initialized()
|
| 1606 |
+
cfg = self.ttt_config
|
| 1607 |
+
if cfg.initial_state_reset:
|
| 1608 |
+
self.ttt_reset()
|
| 1609 |
+
|
| 1610 |
+
device = next(self.parameters()).device
|
| 1611 |
+
tokenized = self._ttt_tokenize(seq=seq, input_ids=input_ids, **kwargs)
|
| 1612 |
+
tokenized = self._ttt_to_device(tokenized, device)
|
| 1613 |
+
generator_device = device if device.type == "cuda" else torch.device("cpu")
|
| 1614 |
+
generator = torch.Generator(device=generator_device)
|
| 1615 |
+
if cfg.seed is not None:
|
| 1616 |
+
generator.manual_seed(cfg.seed)
|
| 1617 |
+
|
| 1618 |
+
module_modes = {module: module.training for module in self.modules()}
|
| 1619 |
+
requires_grad = {param: param.requires_grad for param in self.parameters()}
|
| 1620 |
+
losses: list[float] = []
|
| 1621 |
+
step_metrics: list[dict[str, T.Any]] = []
|
| 1622 |
+
best_state: list[dict[str, torch.Tensor]] | None = None
|
| 1623 |
+
best_metric: float | None = None
|
| 1624 |
+
best_step = 0
|
| 1625 |
+
|
| 1626 |
+
try:
|
| 1627 |
+
self.train()
|
| 1628 |
+
for param in self.parameters():
|
| 1629 |
+
param.requires_grad_(False)
|
| 1630 |
+
for param in self._ttt_lora_parameters():
|
| 1631 |
+
param.requires_grad_(True)
|
| 1632 |
+
|
| 1633 |
+
optimizer = self._ttt_make_optimizer()
|
| 1634 |
+
optimizer.zero_grad(set_to_none=True)
|
| 1635 |
+
total_micro_steps = cfg.steps * cfg.ags
|
| 1636 |
+
for micro_step in range(total_micro_steps):
|
| 1637 |
+
batch, labels = self._ttt_sample_batch(tokenized, generator)
|
| 1638 |
+
logits = self._ttt_predict_logits(batch, **kwargs)
|
| 1639 |
+
labels = labels.to(device=logits.device)
|
| 1640 |
+
loss = F.cross_entropy(
|
| 1641 |
+
logits.reshape(-1, logits.shape[-1]),
|
| 1642 |
+
labels.reshape(-1),
|
| 1643 |
+
ignore_index=-100,
|
| 1644 |
+
)
|
| 1645 |
+
(loss / cfg.ags).backward()
|
| 1646 |
+
if (micro_step + 1) % cfg.ags != 0:
|
| 1647 |
+
continue
|
| 1648 |
+
|
| 1649 |
+
if cfg.gradient_clip:
|
| 1650 |
+
torch.nn.utils.clip_grad_norm_(
|
| 1651 |
+
self._ttt_lora_parameters(),
|
| 1652 |
+
cfg.gradient_clip_max_norm,
|
| 1653 |
+
)
|
| 1654 |
+
optimizer.step()
|
| 1655 |
+
optimizer.zero_grad(set_to_none=True)
|
| 1656 |
+
step = (micro_step + 1) // cfg.ags
|
| 1657 |
+
loss_value = float(loss.detach().item())
|
| 1658 |
+
losses.append(loss_value)
|
| 1659 |
+
if cfg.eval_each_step:
|
| 1660 |
+
metrics, metric = self._ttt_eval_step(
|
| 1661 |
+
step=step,
|
| 1662 |
+
loss=loss_value,
|
| 1663 |
+
seq=seq,
|
| 1664 |
+
input_ids=input_ids,
|
| 1665 |
+
**kwargs,
|
| 1666 |
+
)
|
| 1667 |
+
if len(metrics) > 0:
|
| 1668 |
+
step_metrics.append(metrics)
|
| 1669 |
+
if metric is not None and (
|
| 1670 |
+
best_metric is None or metric > best_metric
|
| 1671 |
+
):
|
| 1672 |
+
best_metric = metric
|
| 1673 |
+
best_step = step
|
| 1674 |
+
best_state = self._ttt_snapshot_lora_state()
|
| 1675 |
+
|
| 1676 |
+
if cfg.automatic_best_state_reset and best_state is not None:
|
| 1677 |
+
self._ttt_restore_lora_state(best_state)
|
| 1678 |
+
finally:
|
| 1679 |
+
for param, value in requires_grad.items():
|
| 1680 |
+
param.requires_grad_(value)
|
| 1681 |
+
for module, training in module_modes.items():
|
| 1682 |
+
module.train(training)
|
| 1683 |
+
|
| 1684 |
+
return {
|
| 1685 |
+
"losses": losses,
|
| 1686 |
+
"step_metrics": step_metrics,
|
| 1687 |
+
"best_step": best_step,
|
| 1688 |
+
"best_metric": best_metric,
|
| 1689 |
+
}
|
| 1690 |
+
|
| 1691 |
import math
|
| 1692 |
|
| 1693 |
import torch
|