Feature Extraction
Transformers
Safetensors
fast_esmfold
protein
structure-prediction
esmfold
test-time-training
custom_code
Instructions to use Synthyra/FastESMFold with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Synthyra/FastESMFold with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="Synthyra/FastESMFold", trust_remote_code=True)# Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Synthyra/FastESMFold", trust_remote_code=True, dtype="auto") - Notebooks
- Google Colab
- Kaggle
Upload modeling_fast_esmfold.py with huggingface_hub
Browse files- modeling_fast_esmfold.py +538 -0
modeling_fast_esmfold.py
CHANGED
|
@@ -399,6 +399,544 @@ def bool_to_additive_mask(
|
|
| 399 |
additive.masked_fill_(bool_mask.logical_not(), float("-inf"))
|
| 400 |
return additive
|
| 401 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 402 |
"""FastESMFold: self-contained ESMFold with FastESM2 attention and opt-in TTT.
|
| 403 |
|
| 404 |
Usage:
|
|
|
|
| 399 |
additive.masked_fill_(bool_mask.logical_not(), float("-inf"))
|
| 400 |
return additive
|
| 401 |
|
| 402 |
+
import typing as T
|
| 403 |
+
from dataclasses import dataclass, fields
|
| 404 |
+
|
| 405 |
+
import torch
|
| 406 |
+
import torch.nn as nn
|
| 407 |
+
import torch.nn.functional as F
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
@dataclass
|
| 411 |
+
class TTTConfig:
|
| 412 |
+
lr: float = 4e-4
|
| 413 |
+
steps: int = 30
|
| 414 |
+
ags: int = 16
|
| 415 |
+
batch_size: int = 2
|
| 416 |
+
mask_ratio: float = 0.15
|
| 417 |
+
crop_size: int = 1024
|
| 418 |
+
bert_leave_prob: float = 0.1
|
| 419 |
+
bert_replace_prob: float = 0.1
|
| 420 |
+
optimizer: str = "sgd"
|
| 421 |
+
momentum: float = 0.0
|
| 422 |
+
weight_decay: float = 0.0
|
| 423 |
+
seed: int | None = 0
|
| 424 |
+
lora_rank: int = 8
|
| 425 |
+
lora_alpha: float = 32.0
|
| 426 |
+
lora_target_replace_module: str | None = None
|
| 427 |
+
lora_target_modules: tuple[str, ...] | None = None
|
| 428 |
+
initial_state_reset: bool = True
|
| 429 |
+
automatic_best_state_reset: bool = False
|
| 430 |
+
eval_each_step: bool = False
|
| 431 |
+
gradient_clip: bool = False
|
| 432 |
+
gradient_clip_max_norm: float = 1.0
|
| 433 |
+
|
| 434 |
+
@classmethod
|
| 435 |
+
def from_kwargs(cls, **kwargs: T.Any) -> "TTTConfig":
|
| 436 |
+
valid_names = {field.name for field in fields(cls)}
|
| 437 |
+
unknown_names = set(kwargs) - valid_names
|
| 438 |
+
assert len(unknown_names) == 0, f"Unknown TTTConfig fields: {sorted(unknown_names)}"
|
| 439 |
+
return cls(**kwargs)
|
| 440 |
+
|
| 441 |
+
def merged(self, overrides: T.Mapping[str, T.Any] | "TTTConfig" | None) -> "TTTConfig":
|
| 442 |
+
if overrides is None:
|
| 443 |
+
return self
|
| 444 |
+
if isinstance(overrides, TTTConfig):
|
| 445 |
+
return overrides
|
| 446 |
+
values = {field.name: self.__dict__[field.name] for field in fields(self)}
|
| 447 |
+
for name, value in overrides.items():
|
| 448 |
+
assert name in values, f"Unknown TTTConfig field: {name}"
|
| 449 |
+
values[name] = value
|
| 450 |
+
return TTTConfig(**values)
|
| 451 |
+
|
| 452 |
+
def verify(self) -> None:
|
| 453 |
+
assert self.lr > 0.0, "TTT learning rate must be positive."
|
| 454 |
+
assert self.steps >= 1, "TTT steps must be >= 1."
|
| 455 |
+
assert self.ags >= 1, "TTT gradient accumulation steps must be >= 1."
|
| 456 |
+
assert self.batch_size >= 1, "TTT batch_size must be >= 1."
|
| 457 |
+
assert 0.0 < self.mask_ratio <= 1.0, "TTT mask_ratio must be in (0, 1]."
|
| 458 |
+
assert self.crop_size >= 1, "TTT crop_size must be >= 1."
|
| 459 |
+
assert self.lora_rank >= 1, "TTT v1 is LoRA-only, so lora_rank must be >= 1."
|
| 460 |
+
assert self.lora_alpha > 0.0, "TTT lora_alpha must be positive."
|
| 461 |
+
assert self.optimizer in {"adamw", "sgd"}, "TTT optimizer must be 'adamw' or 'sgd'."
|
| 462 |
+
assert 0.0 <= self.bert_leave_prob <= 1.0, "bert_leave_prob must be in [0, 1]."
|
| 463 |
+
assert 0.0 <= self.bert_replace_prob <= 1.0, "bert_replace_prob must be in [0, 1]."
|
| 464 |
+
assert self.bert_leave_prob + self.bert_replace_prob <= 1.0, (
|
| 465 |
+
"bert_leave_prob + bert_replace_prob must be <= 1."
|
| 466 |
+
)
|
| 467 |
+
if self.gradient_clip:
|
| 468 |
+
assert self.gradient_clip_max_norm > 0.0, "gradient_clip_max_norm must be positive."
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
class LoraInjectedLinear(nn.Module):
|
| 472 |
+
def __init__(self, linear: nn.Module, rank: int, alpha: float) -> None:
|
| 473 |
+
super().__init__()
|
| 474 |
+
weight = linear._parameters["weight"]
|
| 475 |
+
assert weight.ndim == 2, "LoRA can only wrap 2D linear weights."
|
| 476 |
+
self.linear = linear
|
| 477 |
+
self.linear.requires_grad_(False)
|
| 478 |
+
self.rank = rank
|
| 479 |
+
self.scale = alpha
|
| 480 |
+
in_features = weight.shape[1]
|
| 481 |
+
out_features = weight.shape[0]
|
| 482 |
+
self.lora_down = nn.Linear(in_features, rank, bias=False, dtype=torch.float32)
|
| 483 |
+
self.lora_up = nn.Linear(rank, out_features, bias=False, dtype=torch.float32)
|
| 484 |
+
self.lora_down.to(device=weight.device)
|
| 485 |
+
self.lora_up.to(device=weight.device)
|
| 486 |
+
nn.init.normal_(self.lora_down.weight, std=1.0 / rank)
|
| 487 |
+
nn.init.zeros_(self.lora_up.weight)
|
| 488 |
+
|
| 489 |
+
@property
|
| 490 |
+
def weight(self) -> torch.Tensor:
|
| 491 |
+
return self.linear._parameters["weight"]
|
| 492 |
+
|
| 493 |
+
@property
|
| 494 |
+
def bias(self) -> torch.Tensor | None:
|
| 495 |
+
return self.linear._parameters["bias"]
|
| 496 |
+
|
| 497 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 498 |
+
base = self.linear(x)
|
| 499 |
+
delta = self.lora_up(self.lora_down(x.to(dtype=torch.float32))) * self.scale
|
| 500 |
+
return base + delta.to(dtype=base.dtype)
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
class FastPLMTestTimeTrainingMixin:
|
| 504 |
+
def init_ttt(self, ttt_config: TTTConfig | T.Mapping[str, T.Any] | None = None) -> None:
|
| 505 |
+
base_config = TTTConfig()
|
| 506 |
+
self._ttt_cfg = base_config.merged(ttt_config)
|
| 507 |
+
self._ttt_cfg.verify()
|
| 508 |
+
self._ttt_initialized = False
|
| 509 |
+
self._ttt_initial_state: list[dict[str, torch.Tensor]] | None = None
|
| 510 |
+
|
| 511 |
+
@property
|
| 512 |
+
def ttt_config(self) -> TTTConfig:
|
| 513 |
+
if "_ttt_cfg" not in self.__dict__:
|
| 514 |
+
self.init_ttt()
|
| 515 |
+
return self._ttt_cfg
|
| 516 |
+
|
| 517 |
+
def _ttt_get_trainable_modules(self) -> list[nn.Module]:
|
| 518 |
+
return [self]
|
| 519 |
+
|
| 520 |
+
def _ttt_get_frozen_modules(self) -> list[nn.Module]:
|
| 521 |
+
return []
|
| 522 |
+
|
| 523 |
+
def _ttt_tokenize(
|
| 524 |
+
self,
|
| 525 |
+
seq: str | list[str] | None = None,
|
| 526 |
+
input_ids: torch.Tensor | None = None,
|
| 527 |
+
**kwargs: T.Any,
|
| 528 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 529 |
+
del kwargs
|
| 530 |
+
if input_ids is not None:
|
| 531 |
+
return input_ids
|
| 532 |
+
assert seq is not None, "Pass either seq or input_ids for TTT."
|
| 533 |
+
tokenized = self.tokenizer(seq, return_tensors="pt", padding=True)
|
| 534 |
+
return tokenized["input_ids"]
|
| 535 |
+
|
| 536 |
+
def _ttt_mask_token(self) -> int:
|
| 537 |
+
return int(self.tokenizer.mask_token_id)
|
| 538 |
+
|
| 539 |
+
def _ttt_padding_token(self) -> int:
|
| 540 |
+
return int(self.tokenizer.pad_token_id)
|
| 541 |
+
|
| 542 |
+
def _ttt_replacement_tokens(self, input_ids: torch.Tensor) -> torch.Tensor:
|
| 543 |
+
tokenizer = self.tokenizer
|
| 544 |
+
special_ids = set(tokenizer.all_special_ids)
|
| 545 |
+
vocab_size = int(self.config.vocab_size)
|
| 546 |
+
ids = [idx for idx in range(vocab_size) if idx not in special_ids]
|
| 547 |
+
assert len(ids) > 0, "TTT replacement token set is empty."
|
| 548 |
+
return torch.tensor(ids, device=input_ids.device, dtype=input_ids.dtype)
|
| 549 |
+
|
| 550 |
+
def _ttt_predict_logits(
|
| 551 |
+
self,
|
| 552 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 553 |
+
**kwargs: T.Any,
|
| 554 |
+
) -> torch.Tensor:
|
| 555 |
+
del kwargs
|
| 556 |
+
if isinstance(batch, dict):
|
| 557 |
+
output = self(**batch)
|
| 558 |
+
return output.logits
|
| 559 |
+
attention_mask = batch.ne(self._ttt_padding_token())
|
| 560 |
+
output = self(input_ids=batch, attention_mask=attention_mask)
|
| 561 |
+
return output.logits
|
| 562 |
+
|
| 563 |
+
def _ttt_eval_step(
|
| 564 |
+
self,
|
| 565 |
+
step: int,
|
| 566 |
+
loss: float,
|
| 567 |
+
seq: str | list[str] | None = None,
|
| 568 |
+
input_ids: torch.Tensor | None = None,
|
| 569 |
+
**kwargs: T.Any,
|
| 570 |
+
) -> tuple[dict[str, T.Any], float | None]:
|
| 571 |
+
del step, loss, seq, input_ids, kwargs
|
| 572 |
+
return {}, None
|
| 573 |
+
|
| 574 |
+
def _ttt_is_lora_target(
|
| 575 |
+
self,
|
| 576 |
+
name: str,
|
| 577 |
+
full_name: str,
|
| 578 |
+
module: nn.Module,
|
| 579 |
+
active: bool,
|
| 580 |
+
target_modules: tuple[str, ...] | None,
|
| 581 |
+
) -> bool:
|
| 582 |
+
if not active:
|
| 583 |
+
return False
|
| 584 |
+
if isinstance(module, LoraInjectedLinear):
|
| 585 |
+
return False
|
| 586 |
+
if (
|
| 587 |
+
target_modules is not None
|
| 588 |
+
and name not in target_modules
|
| 589 |
+
and full_name not in target_modules
|
| 590 |
+
):
|
| 591 |
+
return False
|
| 592 |
+
if isinstance(module, nn.Linear):
|
| 593 |
+
return True
|
| 594 |
+
if "weight" not in module._parameters:
|
| 595 |
+
return False
|
| 596 |
+
weight = module._parameters["weight"]
|
| 597 |
+
if weight is None or weight.ndim != 2:
|
| 598 |
+
return False
|
| 599 |
+
return "Linear" in module.__class__.__name__
|
| 600 |
+
|
| 601 |
+
def _ttt_inject_lora(self) -> int:
|
| 602 |
+
cfg = self.ttt_config
|
| 603 |
+
cfg.verify()
|
| 604 |
+
target_class = cfg.lora_target_replace_module
|
| 605 |
+
target_modules = cfg.lora_target_modules
|
| 606 |
+
wrapped = 0
|
| 607 |
+
|
| 608 |
+
def inject(module: nn.Module, prefix: str, active: bool) -> None:
|
| 609 |
+
nonlocal wrapped
|
| 610 |
+
for name, child in list(module.named_children()):
|
| 611 |
+
full_name = f"{prefix}.{name}" if prefix else name
|
| 612 |
+
child_active = active
|
| 613 |
+
if target_class is not None:
|
| 614 |
+
child_active = active or child.__class__.__name__ == target_class
|
| 615 |
+
if self._ttt_is_lora_target(name, full_name, child, child_active, target_modules):
|
| 616 |
+
setattr(
|
| 617 |
+
module,
|
| 618 |
+
name,
|
| 619 |
+
LoraInjectedLinear(child, rank=cfg.lora_rank, alpha=cfg.lora_alpha),
|
| 620 |
+
)
|
| 621 |
+
wrapped += 1
|
| 622 |
+
continue
|
| 623 |
+
inject(child, full_name, child_active)
|
| 624 |
+
|
| 625 |
+
for trainable_module in self._ttt_get_trainable_modules():
|
| 626 |
+
inject(trainable_module, "", target_class is None)
|
| 627 |
+
assert wrapped > 0, "TTT LoRA injection did not find any target modules."
|
| 628 |
+
return wrapped
|
| 629 |
+
|
| 630 |
+
def _ttt_lora_modules(self) -> list[LoraInjectedLinear]:
|
| 631 |
+
return [module for module in self.modules() if isinstance(module, LoraInjectedLinear)]
|
| 632 |
+
|
| 633 |
+
def _ttt_lora_parameters(self) -> list[nn.Parameter]:
|
| 634 |
+
params: list[nn.Parameter] = []
|
| 635 |
+
for module in self._ttt_lora_modules():
|
| 636 |
+
params.extend(module.lora_down.parameters())
|
| 637 |
+
params.extend(module.lora_up.parameters())
|
| 638 |
+
assert len(params) > 0, "TTT has no LoRA parameters."
|
| 639 |
+
return params
|
| 640 |
+
|
| 641 |
+
def _ttt_snapshot_lora_state(self) -> list[dict[str, torch.Tensor]]:
|
| 642 |
+
snapshot = []
|
| 643 |
+
for module in self._ttt_lora_modules():
|
| 644 |
+
snapshot.append(
|
| 645 |
+
{
|
| 646 |
+
"lora_down.weight": module.lora_down.weight.detach().clone(),
|
| 647 |
+
"lora_up.weight": module.lora_up.weight.detach().clone(),
|
| 648 |
+
}
|
| 649 |
+
)
|
| 650 |
+
assert len(snapshot) > 0, "TTT has no LoRA state to snapshot."
|
| 651 |
+
return snapshot
|
| 652 |
+
|
| 653 |
+
def _ttt_restore_lora_state(self, state: list[dict[str, torch.Tensor]]) -> None:
|
| 654 |
+
modules = self._ttt_lora_modules()
|
| 655 |
+
assert len(modules) == len(state), "TTT LoRA state/module count mismatch."
|
| 656 |
+
with torch.no_grad():
|
| 657 |
+
for module, module_state in zip(modules, state):
|
| 658 |
+
module.lora_down.weight.copy_(module_state["lora_down.weight"])
|
| 659 |
+
module.lora_up.weight.copy_(module_state["lora_up.weight"])
|
| 660 |
+
|
| 661 |
+
def _ttt_ensure_initialized(self) -> None:
|
| 662 |
+
if "_ttt_cfg" not in self.__dict__:
|
| 663 |
+
self.init_ttt()
|
| 664 |
+
if self._ttt_initialized:
|
| 665 |
+
return
|
| 666 |
+
self._ttt_inject_lora()
|
| 667 |
+
self._ttt_initial_state = self._ttt_snapshot_lora_state()
|
| 668 |
+
self._ttt_initialized = True
|
| 669 |
+
|
| 670 |
+
def ttt_reset(self) -> None:
|
| 671 |
+
self._ttt_ensure_initialized()
|
| 672 |
+
assert self._ttt_initial_state is not None, "TTT initial state is not available."
|
| 673 |
+
self._ttt_restore_lora_state(self._ttt_initial_state)
|
| 674 |
+
|
| 675 |
+
def _ttt_make_optimizer(self) -> torch.optim.Optimizer:
|
| 676 |
+
cfg = self.ttt_config
|
| 677 |
+
params = self._ttt_lora_parameters()
|
| 678 |
+
if cfg.optimizer == "sgd":
|
| 679 |
+
return torch.optim.SGD(
|
| 680 |
+
params,
|
| 681 |
+
lr=cfg.lr,
|
| 682 |
+
momentum=cfg.momentum,
|
| 683 |
+
weight_decay=cfg.weight_decay,
|
| 684 |
+
)
|
| 685 |
+
return torch.optim.AdamW(params, lr=cfg.lr, weight_decay=cfg.weight_decay)
|
| 686 |
+
|
| 687 |
+
def _ttt_to_device(
|
| 688 |
+
self,
|
| 689 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 690 |
+
device: torch.device,
|
| 691 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 692 |
+
if isinstance(batch, dict):
|
| 693 |
+
return {name: tensor.to(device) for name, tensor in batch.items()}
|
| 694 |
+
return batch.to(device)
|
| 695 |
+
|
| 696 |
+
def _ttt_input_ids_from_batch(
|
| 697 |
+
self,
|
| 698 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 699 |
+
) -> torch.Tensor:
|
| 700 |
+
if isinstance(batch, dict):
|
| 701 |
+
return batch["input_ids"]
|
| 702 |
+
return batch
|
| 703 |
+
|
| 704 |
+
def _ttt_set_input_ids(
|
| 705 |
+
self,
|
| 706 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 707 |
+
input_ids: torch.Tensor,
|
| 708 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 709 |
+
if isinstance(batch, dict):
|
| 710 |
+
updated = dict(batch)
|
| 711 |
+
updated["input_ids"] = input_ids
|
| 712 |
+
return updated
|
| 713 |
+
return input_ids
|
| 714 |
+
|
| 715 |
+
def _ttt_non_special_mask(self, input_ids: torch.Tensor) -> torch.Tensor:
|
| 716 |
+
pad_token = self._ttt_padding_token()
|
| 717 |
+
mask = input_ids.ne(pad_token)
|
| 718 |
+
special_ids = set(self.tokenizer.all_special_ids)
|
| 719 |
+
for special_id in special_ids:
|
| 720 |
+
mask = mask & input_ids.ne(int(special_id))
|
| 721 |
+
return mask
|
| 722 |
+
|
| 723 |
+
def _ttt_sample_crop(
|
| 724 |
+
self,
|
| 725 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 726 |
+
generator: torch.Generator,
|
| 727 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 728 |
+
input_ids = self._ttt_input_ids_from_batch(batch)
|
| 729 |
+
cfg = self.ttt_config
|
| 730 |
+
if input_ids.shape[1] <= cfg.crop_size:
|
| 731 |
+
return batch
|
| 732 |
+
high = input_ids.shape[1] - cfg.crop_size + 1
|
| 733 |
+
start = int(
|
| 734 |
+
torch.randint(
|
| 735 |
+
high,
|
| 736 |
+
(1,),
|
| 737 |
+
generator=generator,
|
| 738 |
+
device=input_ids.device,
|
| 739 |
+
).item()
|
| 740 |
+
)
|
| 741 |
+
end = start + cfg.crop_size
|
| 742 |
+
if isinstance(batch, dict):
|
| 743 |
+
cropped = {}
|
| 744 |
+
for name, tensor in batch.items():
|
| 745 |
+
if tensor.ndim >= 2 and tensor.shape[1] == input_ids.shape[1]:
|
| 746 |
+
cropped[name] = tensor[:, start:end]
|
| 747 |
+
else:
|
| 748 |
+
cropped[name] = tensor
|
| 749 |
+
return cropped
|
| 750 |
+
return input_ids[:, start:end]
|
| 751 |
+
|
| 752 |
+
def _ttt_sample_batch(
|
| 753 |
+
self,
|
| 754 |
+
tokenized: torch.Tensor | dict[str, torch.Tensor],
|
| 755 |
+
generator: torch.Generator,
|
| 756 |
+
) -> tuple[torch.Tensor | dict[str, torch.Tensor], torch.Tensor]:
|
| 757 |
+
cfg = self.ttt_config
|
| 758 |
+
batch = self._ttt_sample_crop(tokenized, generator)
|
| 759 |
+
input_ids = self._ttt_input_ids_from_batch(batch)
|
| 760 |
+
rows = torch.randint(
|
| 761 |
+
input_ids.shape[0],
|
| 762 |
+
(cfg.batch_size,),
|
| 763 |
+
generator=generator,
|
| 764 |
+
device=input_ids.device,
|
| 765 |
+
)
|
| 766 |
+
if isinstance(batch, dict):
|
| 767 |
+
sampled: torch.Tensor | dict[str, torch.Tensor] = {}
|
| 768 |
+
for name, tensor in batch.items():
|
| 769 |
+
if tensor.ndim >= 1 and tensor.shape[0] == input_ids.shape[0]:
|
| 770 |
+
sampled[name] = tensor.index_select(0, rows)
|
| 771 |
+
else:
|
| 772 |
+
sampled[name] = tensor
|
| 773 |
+
else:
|
| 774 |
+
sampled = input_ids.index_select(0, rows)
|
| 775 |
+
|
| 776 |
+
sampled_ids = self._ttt_input_ids_from_batch(sampled)
|
| 777 |
+
labels = sampled_ids.clone()
|
| 778 |
+
non_special = self._ttt_non_special_mask(sampled_ids)
|
| 779 |
+
label_mask = torch.zeros_like(non_special)
|
| 780 |
+
for row_idx in range(sampled_ids.shape[0]):
|
| 781 |
+
candidate_positions = torch.where(non_special[row_idx])[0]
|
| 782 |
+
if candidate_positions.numel() == 0:
|
| 783 |
+
continue
|
| 784 |
+
num_mask = max(1, int(round(candidate_positions.numel() * cfg.mask_ratio)))
|
| 785 |
+
order = torch.randperm(
|
| 786 |
+
candidate_positions.numel(),
|
| 787 |
+
generator=generator,
|
| 788 |
+
device=sampled_ids.device,
|
| 789 |
+
)
|
| 790 |
+
chosen = candidate_positions[order[:num_mask]]
|
| 791 |
+
label_mask[row_idx, chosen] = True
|
| 792 |
+
labels = labels.masked_fill(~label_mask, -100)
|
| 793 |
+
|
| 794 |
+
masked_ids = sampled_ids.clone()
|
| 795 |
+
chosen_positions = torch.where(label_mask)
|
| 796 |
+
if chosen_positions[0].numel() > 0:
|
| 797 |
+
random_values = torch.rand(
|
| 798 |
+
chosen_positions[0].shape,
|
| 799 |
+
generator=generator,
|
| 800 |
+
device=sampled_ids.device,
|
| 801 |
+
)
|
| 802 |
+
leave = random_values < cfg.bert_leave_prob
|
| 803 |
+
replace = (random_values >= cfg.bert_leave_prob) & (
|
| 804 |
+
random_values < cfg.bert_leave_prob + cfg.bert_replace_prob
|
| 805 |
+
)
|
| 806 |
+
mask = ~(leave | replace)
|
| 807 |
+
if mask.any():
|
| 808 |
+
masked_ids[
|
| 809 |
+
chosen_positions[0][mask],
|
| 810 |
+
chosen_positions[1][mask],
|
| 811 |
+
] = self._ttt_mask_token()
|
| 812 |
+
if replace.any():
|
| 813 |
+
replacement_tokens = self._ttt_replacement_tokens(sampled_ids)
|
| 814 |
+
replacement_idx = torch.randint(
|
| 815 |
+
replacement_tokens.shape[0],
|
| 816 |
+
(int(replace.sum().item()),),
|
| 817 |
+
generator=generator,
|
| 818 |
+
device=sampled_ids.device,
|
| 819 |
+
)
|
| 820 |
+
masked_ids[
|
| 821 |
+
chosen_positions[0][replace],
|
| 822 |
+
chosen_positions[1][replace],
|
| 823 |
+
] = replacement_tokens[replacement_idx]
|
| 824 |
+
|
| 825 |
+
return self._ttt_set_input_ids(sampled, masked_ids), labels
|
| 826 |
+
|
| 827 |
+
def ttt(
|
| 828 |
+
self,
|
| 829 |
+
seq: str | list[str] | None = None,
|
| 830 |
+
input_ids: torch.Tensor | None = None,
|
| 831 |
+
ttt_config: TTTConfig | T.Mapping[str, T.Any] | None = None,
|
| 832 |
+
**kwargs: T.Any,
|
| 833 |
+
) -> dict[str, T.Any]:
|
| 834 |
+
if ttt_config is not None:
|
| 835 |
+
if "_ttt_initialized" in self.__dict__ and self._ttt_initialized:
|
| 836 |
+
next_cfg = self.ttt_config.merged(ttt_config)
|
| 837 |
+
assert next_cfg.lora_rank == self.ttt_config.lora_rank, (
|
| 838 |
+
"Changing lora_rank after TTT initialization is not supported."
|
| 839 |
+
)
|
| 840 |
+
assert next_cfg.lora_alpha == self.ttt_config.lora_alpha, (
|
| 841 |
+
"Changing lora_alpha after TTT initialization is not supported."
|
| 842 |
+
)
|
| 843 |
+
assert (
|
| 844 |
+
next_cfg.lora_target_replace_module
|
| 845 |
+
== self.ttt_config.lora_target_replace_module
|
| 846 |
+
), "Changing LoRA target class after TTT initialization is not supported."
|
| 847 |
+
assert next_cfg.lora_target_modules == self.ttt_config.lora_target_modules, (
|
| 848 |
+
"Changing LoRA target modules after TTT initialization is not supported."
|
| 849 |
+
)
|
| 850 |
+
self._ttt_cfg = next_cfg
|
| 851 |
+
else:
|
| 852 |
+
self.init_ttt(ttt_config)
|
| 853 |
+
|
| 854 |
+
self._ttt_ensure_initialized()
|
| 855 |
+
cfg = self.ttt_config
|
| 856 |
+
if cfg.initial_state_reset:
|
| 857 |
+
self.ttt_reset()
|
| 858 |
+
|
| 859 |
+
device = next(self.parameters()).device
|
| 860 |
+
tokenized = self._ttt_tokenize(seq=seq, input_ids=input_ids, **kwargs)
|
| 861 |
+
tokenized = self._ttt_to_device(tokenized, device)
|
| 862 |
+
generator_device = device if device.type == "cuda" else torch.device("cpu")
|
| 863 |
+
generator = torch.Generator(device=generator_device)
|
| 864 |
+
if cfg.seed is not None:
|
| 865 |
+
generator.manual_seed(cfg.seed)
|
| 866 |
+
|
| 867 |
+
module_modes = {module: module.training for module in self.modules()}
|
| 868 |
+
requires_grad = {param: param.requires_grad for param in self.parameters()}
|
| 869 |
+
losses: list[float] = []
|
| 870 |
+
step_metrics: list[dict[str, T.Any]] = []
|
| 871 |
+
best_state: list[dict[str, torch.Tensor]] | None = None
|
| 872 |
+
best_metric: float | None = None
|
| 873 |
+
best_step = 0
|
| 874 |
+
|
| 875 |
+
try:
|
| 876 |
+
self.train()
|
| 877 |
+
for param in self.parameters():
|
| 878 |
+
param.requires_grad_(False)
|
| 879 |
+
for param in self._ttt_lora_parameters():
|
| 880 |
+
param.requires_grad_(True)
|
| 881 |
+
|
| 882 |
+
optimizer = self._ttt_make_optimizer()
|
| 883 |
+
optimizer.zero_grad(set_to_none=True)
|
| 884 |
+
total_micro_steps = cfg.steps * cfg.ags
|
| 885 |
+
for micro_step in range(total_micro_steps):
|
| 886 |
+
batch, labels = self._ttt_sample_batch(tokenized, generator)
|
| 887 |
+
logits = self._ttt_predict_logits(batch, **kwargs)
|
| 888 |
+
labels = labels.to(device=logits.device)
|
| 889 |
+
loss = F.cross_entropy(
|
| 890 |
+
logits.reshape(-1, logits.shape[-1]),
|
| 891 |
+
labels.reshape(-1),
|
| 892 |
+
ignore_index=-100,
|
| 893 |
+
)
|
| 894 |
+
(loss / cfg.ags).backward()
|
| 895 |
+
if (micro_step + 1) % cfg.ags != 0:
|
| 896 |
+
continue
|
| 897 |
+
|
| 898 |
+
if cfg.gradient_clip:
|
| 899 |
+
torch.nn.utils.clip_grad_norm_(
|
| 900 |
+
self._ttt_lora_parameters(),
|
| 901 |
+
cfg.gradient_clip_max_norm,
|
| 902 |
+
)
|
| 903 |
+
optimizer.step()
|
| 904 |
+
optimizer.zero_grad(set_to_none=True)
|
| 905 |
+
step = (micro_step + 1) // cfg.ags
|
| 906 |
+
loss_value = float(loss.detach().item())
|
| 907 |
+
losses.append(loss_value)
|
| 908 |
+
if cfg.eval_each_step:
|
| 909 |
+
metrics, metric = self._ttt_eval_step(
|
| 910 |
+
step=step,
|
| 911 |
+
loss=loss_value,
|
| 912 |
+
seq=seq,
|
| 913 |
+
input_ids=input_ids,
|
| 914 |
+
**kwargs,
|
| 915 |
+
)
|
| 916 |
+
if len(metrics) > 0:
|
| 917 |
+
step_metrics.append(metrics)
|
| 918 |
+
if metric is not None and (
|
| 919 |
+
best_metric is None or metric > best_metric
|
| 920 |
+
):
|
| 921 |
+
best_metric = metric
|
| 922 |
+
best_step = step
|
| 923 |
+
best_state = self._ttt_snapshot_lora_state()
|
| 924 |
+
|
| 925 |
+
if cfg.automatic_best_state_reset and best_state is not None:
|
| 926 |
+
self._ttt_restore_lora_state(best_state)
|
| 927 |
+
finally:
|
| 928 |
+
for param, value in requires_grad.items():
|
| 929 |
+
param.requires_grad_(value)
|
| 930 |
+
for module, training in module_modes.items():
|
| 931 |
+
module.train(training)
|
| 932 |
+
|
| 933 |
+
return {
|
| 934 |
+
"losses": losses,
|
| 935 |
+
"step_metrics": step_metrics,
|
| 936 |
+
"best_step": best_step,
|
| 937 |
+
"best_metric": best_metric,
|
| 938 |
+
}
|
| 939 |
+
|
| 940 |
"""FastESMFold: self-contained ESMFold with FastESM2 attention and opt-in TTT.
|
| 941 |
|
| 942 |
Usage:
|