Run this model with HF Jobs
Run zgcagi/Recurloop-400M on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/zgcagi/Recurloop-400M. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/zgcagi/Recurloop-400M on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/zgcagi/Recurloop-400M. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/zgcagi/Recurloop-400M. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use zgcagi/Recurloop-400M with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use zgcagi/Recurloop-400M with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="zgcagi/Recurloop-400M", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("zgcagi/Recurloop-400M", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use zgcagi/Recurloop-400M with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "zgcagi/Recurloop-400M" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "zgcagi/Recurloop-400M", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/zgcagi/Recurloop-400M
- SGLang
How to use zgcagi/Recurloop-400M with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "zgcagi/Recurloop-400M" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "zgcagi/Recurloop-400M", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "zgcagi/Recurloop-400M" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "zgcagi/Recurloop-400M", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use zgcagi/Recurloop-400M with Docker Model Runner:
docker model run hf.co/zgcagi/Recurloop-400M
Publish the ULT checkpoint, loader, and verified precision metadata
Browse filesFiles changed (8)
- README.mdAdded+13
- config.jsonAdded+21
- configuration_ult.pyAdded+22
- model.safetensorsAdded+3
- modeling_ult.pyAdded+192
- provenance.jsonAdded+12
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded+1
12345678910111213---library_name: transformerstags:- ult- base-model- text-generation---
# ULT-400M
Unified Looped Transformer pretrained on 40B tokens. The checkpoint has 399,771,888 unique parameters and a 4,096-token context window. Training data: Ai2 Dolma 3 Dolmino Mix (100B-1025).
Paper generation uses greedy BF16 with two-pass Parallel KV and eight Core iterations per pass. Source weights retain FP32 precision. See the [code and evaluation repository](https://github.com/USTCKevinF/ULT).123456789101112131415161718192021{ "model_type": "ult", "architectures": [ "ULTForCausalLM" ], "auto_map": { "AutoConfig": "configuration_ult.ULTConfig", "AutoModelForCausalLM": "modeling_ult.ULTForCausalLM" }, "hidden_size": 1536, "stage_depth": 4, "max_position_embeddings": 4096, "vocab_size": 32768, "torch_dtype": "float32", "core_iterations": 8, "passes": 2, "tie_word_embeddings": true, "bos_token_id": 0, "eos_token_id": 1, "pad_token_id": 2}12345678910111213141516171819202122from transformers import PretrainedConfig
class ULTConfig(PretrainedConfig): model_type = "ult"
def __init__(self, hidden_size=1024, stage_depth=2, max_position_embeddings=2048, vocab_size=32768, core_iterations=8, passes=2, norm_eps=1e-5, **kwargs): kwargs.setdefault("tie_word_embeddings", True) kwargs.setdefault("bos_token_id", 0) kwargs.setdefault("eos_token_id", 1) kwargs.setdefault("pad_token_id", 2) super().__init__(**kwargs) self.hidden_size = self.n_embd = hidden_size self.num_attention_heads = hidden_size // 128 self.stage_depth = stage_depth self.max_position_embeddings = max_position_embeddings self.vocab_size = vocab_size self.core_iterations = core_iterations self.passes = passes self.norm_eps = norm_eps
123version https://git-lfs.github.com/spec/v1oid sha256:375f12b8b2f561753db7a71be0b0a93c32586c9410e0b4047a756a375dbeeb45size 1601220000123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192"""Unified Looped Transformer inference in the original checkpoint layout."""import mathfrom types import SimpleNamespace
import torchfrom torch import nnfrom torch.nn import functional as Ffrom transformers import PreTrainedModelfrom transformers.modeling_outputs import CausalLMOutputfrom .configuration_ult import ULTConfig
class RMSNorm(nn.Module): def __init__(self, dim, eps): super().__init__() self.weight = nn.Parameter(torch.ones(dim)) self.eps = eps
def forward(self, x): with torch.autocast(x.device.type, enabled=False): u = x.float() return (u * torch.rsqrt(u.square().mean(-1, keepdim=True) + self.eps)).to(x.dtype) * self.weight
class Router(nn.Module): def __init__(self, d): super().__init__() self.layer_norm = nn.LayerNorm(d, eps=1e-6) self.static_alpha = nn.Parameter(torch.empty(2, 3)) self.static_beta = nn.Parameter(torch.empty(2)) self.dynamic_alpha_fn = nn.Parameter(torch.empty(d, 3)) self.dynamic_beta_fn = nn.Parameter(torch.empty(d)) self.dynamic_alpha_scale = nn.Parameter(torch.empty(1)) self.dynamic_beta_scale = nn.Parameter(torch.empty(1))
def read(self, x): with torch.autocast(x.device.type, enabled=False): h = x.float() z = self.layer_norm(h) a = self.static_alpha + self.dynamic_alpha_scale * torch.tanh(z @ self.dynamic_alpha_fn) b = self.static_beta + self.dynamic_beta_scale * torch.tanh(z @ self.dynamic_beta_fn) y = a.transpose(-1, -2) @ h return y[..., 0, :].to(x.dtype), (y[..., 1:, :], b)
def write(self, x, update, gates): residual, beta = gates with torch.autocast(x.device.type, enabled=False): return (residual + beta.unsqueeze(-1) * update.float().unsqueeze(-2)).to(x.dtype)
def attention(q, k, v): return F.scaled_dot_product_attention(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True).transpose(1, 2)
class Attention(nn.Module): def __init__(self, d): super().__init__() self.c_q = nn.Linear(d, d, bias=False) self.c_k = nn.Linear(d, d, bias=False) self.c_v = nn.Linear(d, d, bias=False) self.c_proj = nn.Linear(d, d, bias=False)
def forward(self, x, freq, attend): q, k, v = [proj(x).unflatten(-1, (-1, 128)) for proj in (self.c_q, self.c_k, self.c_v)] with torch.autocast(x.device.type, enabled=False): r = torch.cat((q, k), dim=2).unflatten(-1, (-1, 2)).float() a, b = r.unbind(-1) c, s = freq.unbind(-1) rotated = torch.stack((a*c-b*s, a*s+b*c), -1).flatten(3).to(q.dtype) q, k = rotated.chunk(2, dim=2) q, k = F.rms_norm(q, (128,)), F.rms_norm(k, (128,)) return self.c_proj(attend(q, k, v).contiguous().flatten(2))
class Block(nn.Module): def __init__(self, d, eps): super().__init__() self.norm_1, self.norm_2 = RMSNorm(d, eps), RMSNorm(d, eps) self.hc_attn, self.hc_mlp = Router(d), Router(d) self.attn = Attention(d) self.mlp = nn.ModuleDict(dict(fc=nn.Linear(d, 4*d, bias=False), proj=nn.Linear(4*d, d, bias=False)))
def forward(self, x, freq, attend): u, gates = self.hc_attn.read(x) x = self.hc_attn.write(x, self.attn(self.norm_1(u), freq, attend), gates) u, gates = self.hc_mlp.read(x) mid = self.mlp.fc(self.norm_2(u)) out = self.mlp.proj(F.relu(mid).square() * 0.5) return self.hc_mlp.write(x, out, gates)
class Injection(nn.Module): def __init__(self, d): super().__init__() self.dt_bias = nn.Parameter(torch.empty(d)) self.A_log = nn.Parameter(torch.empty(d)) self.B = nn.Parameter(torch.empty(d, d))
def forward(self, x, p): dt = F.softplus(self.dt_bias) return x * torch.exp(-dt * torch.exp(self.A_log)) + dt * (p @ self.B.T)
class Trunk(nn.Module): def __init__(self, config): super().__init__() d, eps = config.hidden_size, config.norm_eps self.config = SimpleNamespace(n_embd=d, num_attention_heads=d//128, init=SimpleNamespace(logit_scale=1.0)) self.emb_scale = 1.0 self.register_buffer("freqs_cis", torch.empty(1, config.max_position_embeddings, 1, 64, 2)) self.transformer = nn.ModuleDict(dict(wte=nn.Embedding(config.vocab_size, d), ln_prelude=RMSNorm(d, eps), adapter=Injection(d), C=nn.Linear(d,d,bias=False), ln_f=RMSNorm(d, eps))) for group in ("prelude", "core_block", "coda"): self.transformer[group] = nn.ModuleList(Block(d, eps) for _ in range(config.stage_depth)) self.lm_head = nn.Linear(d, config.vocab_size, bias=False) self.lm_head.weight = self.transformer.wte.weight
def initialize_state(self, template): std = math.sqrt(2 / (5 * template.shape[-1])) state = torch.randn_like(template, memory_format=torch.contiguous_format) return nn.init.trunc_normal_(state, std=std, a=-3*std, b=3*std)
class ULTForCausalLM(PreTrainedModel): config_class = ULTConfig base_model_prefix = "base" _tied_weights_keys = ["base.lm_head.weight"]
def __init__(self, config): super().__init__(config) self.base = Trunk(config) self.U = nn.Linear(config.hidden_size, config.hidden_size, bias=False) self.G = nn.Linear(config.hidden_size, config.hidden_size, bias=False) self.post_init()
def get_input_embeddings(self): return self.base.transformer.wte
def get_output_embeddings(self): return self.base.lm_head
def inject_feedback(self, e, previous, boundary): eps = self.config.norm_eps gate = self.G(F.rms_norm(e, (e.size(-1),), eps=eps)).sigmoid() f = F.rms_norm(self.U(previous)*gate, (e.size(-1),), eps=eps) scale = (e.float().square().mean(-1, keepdim=True) + eps).sqrt() return e + 0.3 * (f * scale.to(f.dtype)).masked_fill(boundary.unsqueeze(-1), 0)
def initial(self, template, update, pass_index, rank=0): devices = [template.device.index] if template.is_cuda else [] with torch.random.fork_rng(devices=devices): torch.manual_seed(42 + 100003*int(update) + 101*rank + 1009*pass_index) return self.base.initialize_state(template)
def trunk(self, z, init, freq, depth, attend=attention): t = self.base.transformer for block in t.prelude: z = block(z, freq, attend) p = t.ln_prelude(z) x = torch.stack((init,init), -2) for _ in range(depth): x = t.adapter(x,p) for block in t.core_block: x = block(x, freq, attend) x = t.C(x) for block in t.coda: x = block(x, freq, attend) return t.ln_f(x.sum(-2))
def forward(self, input_ids, passes=None, depth=None, update=0, rank=0, labels=None, **kwargs): if input_ids.shape[1] > self.config.max_position_embeddings: raise ValueError("Input exceeds the checkpoint context length") mask = kwargs.get("attention_mask") if mask is not None and not bool(mask.all()): raise ValueError("Score unpadded sequences, or group inputs with identical length") e = self.get_input_embeddings()(input_ids) boundary = F.pad(input_ids[:, :-1].eq(1), (1,0), value=True) freq = self.base.freqs_cis[:, :input_ids.size(1)] passes = self.config.passes if passes is None else passes depth = self.config.core_iterations if depth is None else depth if passes < 1 or depth < 1: raise ValueError("passes and depth must be positive") h = None for k in range(passes): second = e if h is None else self.inject_feedback(e, F.pad(h[:, :-1], (0,0,1,0)), boundary) init = self.initial(e, update, k, rank) h = self.trunk(torch.stack((e,second), -2), init, freq, depth) logits = (h @ self.base.lm_head.weight.T).float() loss = None if labels is None else F.cross_entropy(logits[:, :-1].flatten(0,1), labels[:, 1:].flatten()) return CausalLMOutput(loss=loss, logits=logits)
123456789101112{ "training_step": 38147, "training_token_budget": 40, "unique_parameters": 399771888, "context_length": 4096, "source_checkpoint_sha256": "7337ade2a7457496768260ac12ce6a6a44d0bccee00854877ba6aeb6a08ae1e6", "model_sha256": "375f12b8b2f561753db7a71be0b0a93c32586c9410e0b4047a756a375dbeeb45", "tokenizer_sha256": "dd0bcbc161b777e800ef5dbd1e58e2bf4c2a3c0878fd147026cea10e9b512dbf", "tied_weights": { "base.lm_head.weight": "base.transformer.wte.weight" }}1{"tokenizer_class": "PreTrainedTokenizerFast", "model_max_length": 4096, "bos_token": "<|bos|>", "eos_token": "<|eos|>", "pad_token": "<|pad|>", "clean_up_tokenization_spaces": false}README.mdAdded+13
config.jsonAdded+21
configuration_ult.pyAdded+22
model.safetensorsAdded+3
modeling_ult.pyAdded+192
provenance.jsonAdded+12
tokenizer.jsonAdded
tokenizer_config.jsonAdded+1