Text Generation
Transformers
Safetensors
tinylm
gated-deltanet
nsa
native-sparse-attention
hybrid-attention
32k-context
triton
state-space
custom_code
Run this model with HF Jobs
Run OpenModel-Labs/TinyLM-1-Preview 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/OpenModel-Labs/TinyLM-1-Preview. 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/OpenModel-Labs/TinyLM-1-Preview 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/OpenModel-Labs/TinyLM-1-Preview. 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/OpenModel-Labs/TinyLM-1-Preview. 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 OpenModel-Labs/TinyLM-1-Preview with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use OpenModel-Labs/TinyLM-1-Preview with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="OpenModel-Labs/TinyLM-1-Preview", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("OpenModel-Labs/TinyLM-1-Preview", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use OpenModel-Labs/TinyLM-1-Preview with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "OpenModel-Labs/TinyLM-1-Preview" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "OpenModel-Labs/TinyLM-1-Preview", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/OpenModel-Labs/TinyLM-1-Preview
- SGLang
How to use OpenModel-Labs/TinyLM-1-Preview 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 "OpenModel-Labs/TinyLM-1-Preview" \ --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": "OpenModel-Labs/TinyLM-1-Preview", "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 "OpenModel-Labs/TinyLM-1-Preview" \ --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": "OpenModel-Labs/TinyLM-1-Preview", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use OpenModel-Labs/TinyLM-1-Preview with Docker Model Runner:
docker model run hf.co/OpenModel-Labs/TinyLM-1-Preview
feat: pure-PyTorch GDN fallback (fla optional)
#2
by Bc-AI - opened
Files changed (2)
- README.md+1-1
- modeling_TinyLM.py+196-10
53 unmodified lines5455565758596053 unmodified linesprint(tok.decode(out[0]))```Requirements: `torch>=2.5`, `transformers>=4.46` (tested with 5.25), `flash-linear-attention` (tested with 0.6), `triton` (CUDA). GDN layers require a CUDA GPU; NSA layers also run on CPU.Generation re-processes the full sequence each step (no KV cache — `use_cache=False` by design);this is a preview, not a serving build.53 unmodified lines5455565758596053 unmodified linesprint(tok.decode(out[0]))```Requirements: `torch>=2.5`, `transformers>=4.46` (tested with 5.25). `flash-linear-attention` (tested with 0.6) is optional — used as a fast path when installed; otherwise a built-in pure-PyTorch GDN fallback runs on CPU or GPU. `triton` is only needed for the fla fast path (CUDA).Generation re-processes the full sequence each step (no KV cache — `use_cache=False` by design);this is a preview, not a serving build.
4 unmodified lines567891011305 unmodified lines3173183193203213223233243253263273283293303313323333344 unmodified linesembed.weight, norm.weight, blocks.{i}.{n1,n2,w13,w2}.*, and eitherblocks.{i}.mix.layer.* (G = GatedDeltaNet) or blocks.{i}.mix.* (N = NSA).Requirements: torch>=2.5 (flex_attention), flash-linear-attention (fla), triton (CUDA)."""import osfrom typing import Optional, Tuple, Union305 unmodified linesreturn x + F.linear(F.silu(g) * u, w2)class GDNMixer(nn.Module):def __init__(self, cfg: TinyLMConfig, idx: int):super().__init__()try:from fla.layers import GatedDeltaNetexcept ImportError as e:raise ImportError("TinyLM G-layers require flash-linear-attention: `pip install flash-linear-attention`") from eself.layer = GatedDeltaNet(hidden_size=cfg.d_model, expand_v=cfg.gdn_expand_v, head_dim=cfg.gdn_head_dim,num_heads=cfg.gdn_heads, mode="chunk", use_gate=True, use_short_conv=True,conv_size=4, layer_idx=idx)def forward(self, x):return self.layer(x)[0]4 unmodified lines567891011305 unmodified lines3173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195204 unmodified linesembed.weight, norm.weight, blocks.{i}.{n1,n2,w13,w2}.*, and eitherblocks.{i}.mix.layer.* (G = GatedDeltaNet) or blocks.{i}.mix.* (N = NSA).Requirements: torch>=2.5 (flex_attention). flash-linear-attention is optional (fast path when installed); a pure-PyTorch GDN fallback is built in."""import osfrom typing import Optional, Tuple, Union305 unmodified linesreturn x + F.linear(F.silu(g) * u, w2)def _gdn_recurrent(q, k, v, beta, g, scale=None):"""Pure-PyTorch gated delta rule (recurrent), fla `state_v_first` math.q,k: [B,T,H,K]; v: [B,T,H,V]; beta,g: [B,T,H] (post-sigmoid / log-decay).Returns o: [B,T,H,V]. Computed in fp32 like the fla kernel."""q = q.transpose(1, 2).float()k = k.transpose(1, 2).float()v = v.transpose(1, 2).float()beta = beta.transpose(1, 2).float()g = g.transpose(1, 2).float()B, H, T, K = q.shapeV = v.shape[-1]if scale is None:scale = K ** -0.5q = q * scaleo = torch.zeros(B, H, T, V, dtype=torch.float32, device=q.device)h = torch.zeros(B, H, K, V, dtype=torch.float32, device=q.device)for t in range(T):b_q, b_k, b_v, b_beta = q[:, :, t], k[:, :, t], v[:, :, t], beta[:, :, t]# decay first (natural exp of per-step log decay), then delta, then read outh = h * g[:, :, t].exp().unsqueeze(-1).unsqueeze(-1)b_v = b_v - (h * b_k.unsqueeze(-1)).sum(-2)b_v = b_v * b_beta.unsqueeze(-1)h = h + b_k.unsqueeze(-1) * b_v.unsqueeze(-2)o[:, :, t] = torch.einsum("bhk,bhkv->bhv", b_q, h)return o.transpose(1, 2)class PureRMSNormGated(nn.Module):"""fla FusedRMSNormGated drop-in: rms_norm(x)*weight * silu(g). Same `.weight` key."""def __init__(self, hidden_size: int, eps: float = 1e-5):super().__init__()self.weight = nn.Parameter(torch.ones(hidden_size))self.eps = epsdef forward(self, x: torch.Tensor, g: torch.Tensor) -> torch.Tensor:dtype = x.dtypex = F.rms_norm(x.float(), (x.size(-1),), self.weight.float(), self.eps)return (x * F.silu(g.float())).to(dtype)class PureGatedDeltaNet(nn.Module):"""Pure-PyTorch GatedDeltaNet with parameter names identical to fla.layers.GatedDeltaNet.Used when flash-linear-attention (or its triton dependency) is unavailable."""def __init__(self,hidden_size: int = 2048,expand_v: float = 2,head_dim: int = 256,num_heads: int = 6,num_v_heads: Optional[int] = None,mode: str = "chunk",use_gate: bool = True,use_short_conv: bool = True,allow_neg_eigval: bool = False,conv_size: int = 4,conv_bias: bool = False,layer_idx: Optional[int] = None,norm_eps: float = 1e-5,output_gate_activation: str = "swish",**kwargs,):super().__init__()self.mode = modeself.allow_neg_eigval = allow_neg_eigvalself.use_gate = use_gateself.use_short_conv = use_short_convself.conv_size = conv_sizeself.head_dim = head_dimself.num_heads = num_headsself.num_v_heads = num_heads if num_v_heads is None else num_v_headsself.head_k_dim = head_dimself.head_v_dim = int(head_dim * expand_v)self.key_dim = int(num_heads * self.head_k_dim)self.value_dim = int(self.num_v_heads * self.head_v_dim)self.layer_idx = layer_idxself.norm_eps = norm_epsself.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)self.a_proj = nn.Linear(hidden_size, self.num_v_heads, bias=False)self.b_proj = nn.Linear(hidden_size, self.num_v_heads, bias=False)# Match fla init (overwritten when loading a checkpoint)import math as _mathA = torch.empty(self.num_v_heads, dtype=torch.float32).uniform_(0, 16)self.A_log = nn.Parameter(torch.log(A))dt = torch.exp(torch.rand(self.num_v_heads) * (_math.log(0.1) - _math.log(0.001)) + _math.log(0.001))dt = torch.clamp(dt, min=1e-4)self.dt_bias = nn.Parameter(dt + torch.log(-torch.expm1(-dt)))if use_short_conv:# Weight layout matches fla ShortConvolution: [C, 1, kernel] (depthwise)self.q_conv1d = nn.Conv1d(self.key_dim, self.key_dim, conv_size,padding=conv_size - 1, groups=self.key_dim, bias=conv_bias)self.k_conv1d = nn.Conv1d(self.key_dim, self.key_dim, conv_size,padding=conv_size - 1, groups=self.key_dim, bias=conv_bias)self.v_conv1d = nn.Conv1d(self.value_dim, self.value_dim, conv_size,padding=conv_size - 1, groups=self.value_dim, bias=conv_bias)if use_gate:self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)self.o_norm = PureRMSNormGated(self.head_v_dim, eps=norm_eps)self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)@staticmethoddef _causal_silu_conv(x: torch.Tensor, conv: nn.Conv1d) -> torch.Tensor:"""Depthwise causal conv + silu; x is [B,T,C]. Uses weight tap like fla causal_conv1d."""w = conv.weight # [C,1,K]K = w.shape[-1]xt = x.transpose(1, 2) # [B,C,T]# left-pad only so output[t] depends on x[t-K+1..t]xt = F.pad(xt, (K - 1, 0))yt = F.conv1d(xt, w, bias=conv.bias, groups=w.shape[0])# trim right overhang from symmetric padding simulation: length is T already after left-pad+conv# F.pad(K-1,0) + conv(K) -> T; no trim neededreturn F.silu(yt).transpose(1, 2)def forward(self,hidden_states: torch.Tensor,attention_mask=None,past_key_values=None,use_cache: bool = False,output_attentions: bool = False,**kwargs,):B, T, _ = hidden_states.shapeif self.use_short_conv:q = self._causal_silu_conv(self.q_proj(hidden_states), self.q_conv1d)k = self._causal_silu_conv(self.k_proj(hidden_states), self.k_conv1d)v = self._causal_silu_conv(self.v_proj(hidden_states), self.v_conv1d)else:q = F.silu(self.q_proj(hidden_states))k = F.silu(self.k_proj(hidden_states))v = F.silu(self.v_proj(hidden_states))q = q.view(B, T, self.num_heads, self.head_k_dim)k = k.view(B, T, self.num_heads, self.head_k_dim)v = v.view(B, T, self.num_v_heads, self.head_v_dim)beta = self.b_proj(hidden_states) # raw logits; sigmoid belowg_raw = self.a_proj(hidden_states) # raw; gate transform below# l2norm q,k (eps=1e-6, matches fla kernel) then scale on q inside _gdn_recurrentq = q / torch.sqrt((q * q).sum(-1, keepdim=True) + 1e-6)k = k / torch.sqrt((k * k).sum(-1, keepdim=True) + 1e-6)beta = torch.sigmoid(beta)if self.allow_neg_eigval:beta = beta * 2# g = -exp(A_log) * softplus(g_raw + dt_bias) -> per-step log decayg = -torch.exp(self.A_log.float()) * F.softplus(g_raw.float() + self.dt_bias.float())o = _gdn_recurrent(q, k, v, beta, g, scale=self.head_k_dim ** -0.5) # [B,T,HV,V]if self.use_gate:g_out = self.g_proj(hidden_states).view(B, T, self.num_v_heads, self.head_v_dim)o = self.o_norm(o, g_out)else:o = F.rms_norm(o.float(), (o.size(-1),), self.o_norm.weight.float(), self.o_norm.eps).to(o.dtype)o = o.reshape(B, T, self.value_dim)o = self.o_proj(o)return o, None, Nonedef _build_gdn_layer(cfg: TinyLMConfig, idx: int) -> nn.Module:"""fla fast path when importable; pure-PyTorch fallback otherwise."""kwargs = dict(hidden_size=cfg.d_model,expand_v=cfg.gdn_expand_v,head_dim=cfg.gdn_head_dim,num_heads=cfg.gdn_heads,mode="chunk",use_gate=True,use_short_conv=True,conv_size=4,layer_idx=idx,)if os.environ.get("TINLM_FORCE_PURE_GDN") != "1":try:from fla.layers import GatedDeltaNetreturn GatedDeltaNet(**kwargs)except Exception:passreturn PureGatedDeltaNet(**kwargs)class GDNMixer(nn.Module):def __init__(self, cfg: TinyLMConfig, idx: int):super().__init__()self.layer = _build_gdn_layer(cfg, idx)def forward(self, x):return self.layer(x)[0]
README.md+1-1
modeling_TinyLM.py+196-10