Upload folder using huggingface_hub
Browse filesFiles changed (8)
- .gitattributes+1
- README.mdAdded+32
- chat_template.jinjaAdded+54
- config.jsonAdded+28
- inference.pyAdded+117
- model.safetensorsAdded+3
- tokenizer.jsonAdded+3
- tokenizer_config.jsonAdded+30
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text
1234567891011121314151617181920212223242526272829303132---language:- tr- entags:- looped-transformer- from-scratch- multi-token-prediction- reasoning- tool-use- pytorchlicense: apache-2.0---
# Loop7B v3 — `v0.1` (From-Scratch Dynamic 4-Loop Transformer)
**Loop7B v3 (`v0.1`)** is an experimental **6.85B-parameter Looped Transformer** trained **100% from scratch** on a single GPU (Google Colab Pro+ A100-80GB & G4 Blackwell).
It features **dynamic test-time compute depth** (`low=1`, `medium=2`, `high=3`, `xhigh=4` loops -> `32 / 64 / 96 / 128` effective Transformer layers), **Multi-Token Prediction (MTP)** pretraining, **Input Re-Injection**, **`<think>...</think>`** reasoning, and **`<tool_call>`** structured tool calling in **Turkish & English**.
> **Note (`v0.1` Research Preview):** This `v0.1` checkpoint is the first end-to-end milestone (**1.0B** Stage 1 pretraining tokens + **Stage 2A** 4-Loop adaptation + **Stage 2B** SFT). Future releases (`v0.2`, `v0.3`, ..., `v1.0`) will scale Stage 1 pretraining to multi-billion tokens.
## Architecture Highlights- **Parameters:** 6.85B physical (`dim=4096`, `core_layers=32`, `n_heads=32`, `n_kv_heads=8` GQA, `ffn_dim=12288` SwiGLU, RoPE `theta=500000`, tied embeddings)- **Dynamic Loop Depth:** `low=1` (32L), `medium=2` (64L), `high=3` (96L), `xhigh=4` (128L)- **Pipeline:** Stage 1 (1.00B tokens, MTP) -> Stage 2A (1,500 steps, 2->3->4 loop curriculum) -> Stage 2B (1,200 steps ChatML SFT)
## Quick Start```pythonfrom inference import load_loop7bmodel, tokenizer = load_loop7b("tm1324/Loop7B-v3-v0.1", device="cuda")```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354{%- if tools %} {{- '<|im_start|>system\n' }} {%- if messages[0]['role'] == 'system' %} {{- messages[0]['content'] }} {%- else %} {{- 'You are a helpful assistant.' }} {%- endif %} {{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }} {%- for tool in tools %} {{- "\n" }} {{- tool | tojson }} {%- endfor %} {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}{%- else %} {%- if messages[0]['role'] == 'system' %} {{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }} {%- else %} {{- '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }} {%- endif %}{%- endif %}{%- for message in messages %} {%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) %} {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }} {%- elif message.role == "assistant" %} {{- '<|im_start|>' + message.role }} {%- if message.content %} {{- '\n' + message.content }} {%- endif %} {%- for tool_call in message.tool_calls %} {%- if tool_call.function is defined %} {%- set tool_call = tool_call.function %} {%- endif %} {{- '\n<tool_call>\n{"name": "' }} {{- tool_call.name }} {{- '", "arguments": ' }} {{- tool_call.arguments | tojson }} {{- '}\n</tool_call>' }} {%- endfor %} {{- '<|im_end|>\n' }} {%- elif message.role == "tool" %} {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %} {{- '<|im_start|>user' }} {%- endif %} {{- '\n<tool_response>\n' }} {{- message.content }} {{- '\n</tool_response>' }} {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} {{- '<|im_end|>\n' }} {%- endif %} {%- endif %}{%- endfor %}{%- if add_generation_prompt %} {{- '<|im_start|>assistant\n' }}{%- endif %}12345678910111213141516171819202122232425262728{ "architectures": [ "Loop7Bv3Model" ], "model_type": "loop7b_v3", "version": "v0.1", "vocab_size": 151680, "dim": 4096, "core_layers": 32, "n_heads": 32, "n_kv_heads": 8, "ffn_dim": 12288, "max_loops": 4, "effort_map": { "low": 1, "medium": 2, "high": 3, "xhigh": 4 }, "mtp_heads": 4, "rope_theta": 500000.0, "max_seq_len": 1024, "tie_word_embeddings": true, "torch_dtype": "bfloat16", "stage1_tokens": "1.0B", "stage2a_steps": 1500, "stage2b_sft_steps": 1200}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import torchimport torch.nn as nnimport torch.nn.functional as Ffrom safetensors.torch import load_filefrom transformers import AutoTokenizerfrom huggingface_hub import hf_hub_download
EFFORT_MAP = {"low": 1, "medium": 2, "high": 3, "xhigh": 4}DEFAULT_SYS = ( "Sen Loop7B v3 adında, dinamik 4-döngülü (Looped Transformer) Türkçe ve İngilizce " "akıllı bir yapay zeka asistanısın. Karmaşık sorularda <think>...</think> içinde adım adım " "düşün, araç gerektiğinde <tool_call> kullan, emin olmadığın konularda bilmediğini dürüstçe söyle.")
class RMSNorm(nn.Module): def __init__(self, dim, eps=1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(dim)) self.eps = eps def forward(self, x): xf = x.float() return (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps)).to(x.dtype) * self.weight
def precompute_rope(head_dim, max_seq_len=1024, theta=500000.0, dtype=torch.bfloat16): freqs = 1.0 / (theta ** (torch.arange(0, head_dim, 2, dtype=torch.float32) / head_dim)) angles = torch.outer(torch.arange(max_seq_len, dtype=torch.float32), freqs) c, s = torch.cos(angles).to(dtype), torch.sin(angles).to(dtype) return torch.cat((c, c), dim=-1), torch.cat((s, s), dim=-1)
def apply_rope(x, cos, sin): T = x.size(2) c, s = cos[:T].unsqueeze(0).unsqueeze(0), sin[:T].unsqueeze(0).unsqueeze(0) x1, x2 = x.chunk(2, dim=-1) return (x * c) + (torch.cat((-x2, x1), dim=-1) * s)
class GQAAttention(nn.Module): def __init__(self, dim=4096, n_heads=32, n_kv_heads=8): super().__init__() self.n_heads, self.n_kv_heads = n_heads, n_kv_heads self.n_rep, self.head_dim = n_heads // n_kv_heads, dim // n_heads self.q_proj = nn.Linear(dim, n_heads * self.head_dim, bias=False) self.k_proj = nn.Linear(dim, n_kv_heads * self.head_dim, bias=False) self.v_proj = nn.Linear(dim, n_kv_heads * self.head_dim, bias=False) self.o_proj = nn.Linear(dim, dim, bias=False) def forward(self, x, cos, sin): B, T, C = x.shape q = apply_rope(self.q_proj(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2), cos, sin) k = apply_rope(self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2), cos, sin) v = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2) if self.n_rep > 1: k = k.repeat_interleave(self.n_rep, dim=1) v = v.repeat_interleave(self.n_rep, dim=1) out = F.scaled_dot_product_attention(q, k, v, is_causal=True) return self.o_proj(out.transpose(1, 2).contiguous().view(B, T, C))
class SwiGLUMLP(nn.Module): def __init__(self, dim=4096, ffn_dim=12288): super().__init__() self.gate_proj = nn.Linear(dim, ffn_dim, bias=False) self.up_proj = nn.Linear(dim, ffn_dim, bias=False) self.down_proj = nn.Linear(ffn_dim, dim, bias=False) def forward(self, x): return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
class LoopedBlock(nn.Module): def __init__(self, dim=4096, n_heads=32, n_kv_heads=8, ffn_dim=12288): super().__init__() self.norm1, self.attn = RMSNorm(dim), GQAAttention(dim, n_heads, n_kv_heads) self.norm2, self.mlp = RMSNorm(dim), SwiGLUMLP(dim, ffn_dim) def forward(self, x, step_emb, cos, sin): x = x + self.attn(self.norm1(x + step_emb), cos, sin) x = x + self.mlp(self.norm2(x)) return x
class Loop7Bv3Model(nn.Module): def __init__(self, vocab_size=151680, dim=4096, core_layers=32, n_heads=32, n_kv_heads=8, ffn_dim=12288, max_loops=4, mtp_heads=4, max_seq_len=1024, dtype=torch.bfloat16): super().__init__() self.embed = nn.Embedding(vocab_size, dim) self.loop_embs = nn.Parameter(torch.zeros(max_loops, 1, 1, dim)) self.loop_alpha = nn.Parameter(torch.tensor(0.05)) self.layers = nn.ModuleList([LoopedBlock(dim, n_heads, n_kv_heads, ffn_dim) for _ in range(core_layers)]) self.norm = RMSNorm(dim) self.mtp_projs = nn.ModuleList([ nn.Identity() if k == 0 else nn.Sequential(RMSNorm(dim), nn.Linear(dim, dim, bias=False)) for k in range(mtp_heads) ]) self.lm_head = nn.Linear(dim, vocab_size, bias=False) self.lm_head.weight = self.embed.weight cos, sin = precompute_rope(dim // n_heads, max_seq_len=max_seq_len, dtype=dtype) self.register_buffer("rope_cos", cos, persistent=False) self.register_buffer("rope_sin", sin, persistent=False)
@torch.inference_mode() def forward_logits(self, input_ids, num_loops=2): x_embed = self.embed(input_ids) xf = x_embed.float() x_inj = (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + 1e-6)).to(x_embed.dtype) x = x_embed for l in range(num_loops): if l > 0: x = x + self.loop_alpha.to(x.dtype) * x_inj for layer in self.layers: x = layer(x, self.loop_embs[l], self.rope_cos, self.rope_sin) return self.lm_head(self.norm(x)[:, -1:, :])
def load_loop7b(repo_id, device="cuda", dtype=torch.bfloat16): tokenizer = AutoTokenizer.from_pretrained(repo_id) weights_path = hf_hub_download(repo_id=repo_id, filename="model.safetensors") sd = {k: v.to(dtype) for k, v in load_file(weights_path).items()} with torch.device("meta"): model = Loop7Bv3Model(dtype=dtype) model.to_empty(device="cpu") model.load_state_dict(sd, strict=False, assign=True) model.lm_head.weight = model.embed.weight model.rope_cos, model.rope_sin = precompute_rope(128, max_seq_len=1024, dtype=dtype) return model.to(device=device, dtype=dtype).eval(), tokenizer123version https://git-lfs.github.com/spec/v1oid sha256:d166384015451b7d9bd056211e63b3654cf993c078d0bc1cb086e72d9ebe969dsize 13691878004123version https://git-lfs.github.com/spec/v1oid sha256:3fd169731d2cbde95e10bf356d66d5997fd885dd8dbb6fb4684da3f23b2585d8size 11421892123456789101112131415161718192021222324252627282930{ "add_prefix_space": false, "backend": "tokenizers", "bos_token": null, "clean_up_tokenization_spaces": false, "eos_token": "<|endoftext|>", "errors": "replace", "extra_special_tokens": [ "<|im_start|>", "<|im_end|>", "<|object_ref_start|>", "<|object_ref_end|>", "<|box_start|>", "<|box_end|>", "<|quad_start|>", "<|quad_end|>", "<|vision_start|>", "<|vision_end|>", "<|vision_pad|>", "<|image_pad|>", "<|video_pad|>" ], "is_local": false, "local_files_only": false, "model_max_length": 131072, "pad_token": "<|endoftext|>", "split_special_tokens": false, "tokenizer_class": "Qwen2Tokenizer", "unk_token": null}.gitattributes+1
README.mdAdded+32
chat_template.jinjaAdded+54
config.jsonAdded+28
inference.pyAdded+117
model.safetensorsAdded+3
tokenizer.jsonAdded+3
tokenizer_config.jsonAdded+30