Run this model with HF Jobs
Run zgcagi/Recurloop-113M 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-113M. 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-113M 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-113M. 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-113M. 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-113M with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use zgcagi/Recurloop-113M with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="zgcagi/Recurloop-113M", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("zgcagi/Recurloop-113M", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use zgcagi/Recurloop-113M with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "zgcagi/Recurloop-113M" # 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-113M", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/zgcagi/Recurloop-113M
- SGLang
How to use zgcagi/Recurloop-113M 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-113M" \ --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-113M", "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-113M" \ --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-113M", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use zgcagi/Recurloop-113M with Docker Model Runner:
docker model run hf.co/zgcagi/Recurloop-113M
Rename model_type/config/modeling modules from ult to recurloop (RecurloopConfig, RecurloopForCausalLM)
182b69e verified Download modeling_recurloop.py from zgcagi/Recurloop-113M: direct link, hf CLI and curl.
- Browser
- Download file 9.15 kB
-
https://huggingface.co/zgcagi/Recurloop-113M/resolve/main/modeling_recurloop.py
- Command line
-
hf download hf://zgcagi/Recurloop-113M/modeling_recurloop.py
-
curl -L -o modeling_recurloop.py https://huggingface.co/zgcagi/Recurloop-113M/resolve/main/modeling_recurloop.py
9.15 kB
| """Recurloop Transformer inference in the checkpoint layout.""" | |
| import math | |
| from types import SimpleNamespace | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| from transformers import GenerationMixin, PreTrainedModel | |
| from transformers.modeling_outputs import CausalLMOutput | |
| from .configuration_recurloop import RecurloopConfig | |
| 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() | |
| w = None if self.layer_norm.weight is None else self.layer_norm.weight.float() | |
| bias = None if self.layer_norm.bias is None else self.layer_norm.bias.float() | |
| z = F.layer_norm(h, self.layer_norm.normalized_shape, w, bias, self.layer_norm.eps) | |
| a = self.static_alpha.float() + self.dynamic_alpha_scale.float() * torch.tanh(z @ self.dynamic_alpha_fn.float()) | |
| b = self.static_beta.float() + self.dynamic_beta_scale.float() * torch.tanh(z @ self.dynamic_beta_fn.float()) | |
| 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.float().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 RecurloopForCausalLM(PreTrainedModel, GenerationMixin): | |
| config_class = RecurloopConfig | |
| 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 prepare_inputs_for_generation(self, input_ids, attention_mask=None, **kwargs): | |
| out = {"input_ids": input_ids} | |
| if attention_mask is not None: | |
| out["attention_mask"] = attention_mask | |
| return out | |
| 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, | |
| attention_mask=None, | |
| token_type_ids=None, | |
| use_cache=None, | |
| passes=None, | |
| depth=None, | |
| update=0, | |
| rank=0, | |
| labels=None, | |
| initial_order=None, | |
| **kwargs, | |
| ): | |
| if input_ids.shape[1] > self.config.max_position_embeddings: | |
| raise ValueError("Input exceeds the checkpoint context length") | |
| if attention_mask is not None and not bool(attention_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) | |
| if initial_order is not None: | |
| init = init.index_select(0, torch.as_tensor(initial_order, device=init.device)) | |
| 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) | |