Run this model with HF Jobs
Run Prositron/Freearch 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/Prositron/Freearch. 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/Prositron/Freearch 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/Prositron/Freearch. 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/Prositron/Freearch. 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 Prositron/Freearch with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Prositron/Freearch with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Prositron/Freearch")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Prositron/Freearch", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Prositron/Freearch with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Prositron/Freearch" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Prositron/Freearch", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/Prositron/Freearch
- SGLang
How to use Prositron/Freearch 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 "Prositron/Freearch" \ --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": "Prositron/Freearch", "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 "Prositron/Freearch" \ --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": "Prositron/Freearch", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use Prositron/Freearch with Docker Model Runner:
docker model run hf.co/Prositron/Freearch
Delete model.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211import torchimport torch.nn as nnimport torch.nn.functional as Fimport bitsandbytes as bnbfrom dataclasses import dataclassfrom bitsandbytes.nn.modules import Linear8bitLt as QuantLinearimport math
class QuantLinear(nn.Linear): def __init__(self, in_features, out_features, bias=True): super().__init__(in_features, out_features, bias)# -----------------------------------------------------------------------------
# ββ Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@dataclassclass FreearchConfig: vocab_size: int = 50257 max_seq_len: int = 4096 hidden_size: int = 768 num_layers: int = 12 ff_size: int = 6000 num_experts: int = 36 top_k: int = 14 idea_dim: int = 32 num_ideas: int = 16 emotion_dim: int = 154 # no flag neededβalways 2-bit now
# ββ RMSNorm βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββclass RMSNorm(nn.Module): def __init__(self, hidden_size, eps=1e-8): super().__init__() self.eps = eps self.scale = nn.Parameter(torch.ones(hidden_size)) def forward(self, x): # x shape: (batch..., hidden_size) variance = torch.mean(x.pow(2), dim=-1, keepdim=True) inv_rms = torch.rsqrt(variance + self.eps) return x * (inv_rms * self.scale)# ββ Expert ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββclass Expert(nn.Module): def __init__(self, d, ff): super().__init__() self.fc1 = QuantLinear(d, ff, bias=True) self.fc2 = QuantLinear(ff, d, bias=True) self.rank = 64 self.lora_A = nn.Parameter(torch.randn(d, self.rank) * 0.01) self.lora_B = nn.Parameter(torch.randn(self.rank, d) * 0.01) # @torch._dynamo.disable # This decorator is no longer strictly necessary with nn.Linear, but kept for context. def forward(self, x): out = F.silu(self.fc1(x)) out = self.fc2(out) lora_output = x @ self.lora_A @ self.lora_B return out + lora_output
# ββ MoE βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββclass MoE(nn.Module): def __init__(self, cfg: FreearchConfig): super().__init__() self.experts = nn.ModuleList( [Expert(cfg.hidden_size, cfg.ff_size) for _ in range(cfg.num_experts)] ) self.top_k = cfg.top_k self.router = nn.Linear(cfg.hidden_size, cfg.num_experts) def forward(self, x): B, T, H = x.size() flat = x.view(-1, H) # Flatten for routing and expert processing logits = self.router(flat) # Router scores for each expert topk, idx = torch.topk(logits, self.top_k, dim=-1) # Select top-k experts wts = F.softmax(topk, dim=-1) # Softmax to get gating weights # Initialize output tensor out = torch.zeros_like(flat) # Iterate over each of the top-k selected experts for i in range(self.top_k): expert_idx = idx[:, i] # Get the index of the i-th chosen expert for each token w = wts[:, i].unsqueeze(1) # Get the corresponding weight for this expert # Process tokens for each expert for e, expert in enumerate(self.experts): mask = (expert_idx == e) # Create a mask for tokens assigned to this specific expert 'e' if not mask.any(): continue # Skip if no tokens are assigned to this expert inp = flat[mask] # Select input tokens for this expert res = expert(inp) # Process through the expert out[mask] += w[mask] * res # Add weighted output to the overall output
return out.view(B, T, H) # Reshape back to original (B, T, H)# ββ BrainModule βββββββββββββββββββββββββββββββββββββββββββββββββββββββββclass BrainModule(nn.Module): def __init__(self, d, idea_dim, num_ideas, num_heads=4): super().__init__() self.num_heads = num_heads assert idea_dim % num_heads == 0, "idea_dim must be divisible by num_heads" self.head_dim = idea_dim // num_heads self.num_ideas = num_ideas
self.idea_pool = nn.Parameter(torch.randn(num_ideas, idea_dim)) self.to_query = QuantLinear(d, idea_dim, bias=True) self.to_key = QuantLinear(idea_dim, idea_dim, bias=True) self.to_value = QuantLinear(idea_dim, idea_dim, bias=True) self.out_proj = QuantLinear(idea_dim, d, bias=True)
self.ln = RMSNorm(idea_dim) self.fc1 = QuantLinear(idea_dim, idea_dim * 2, bias=True) self.fc2 = QuantLinear(idea_dim, idea_dim, bias=True)
def forward(self, x, use_generator=True): B, T, d = x.size() flat_x = x.view(-1, d) # (B*T, d)
# queries Q = self.to_query(flat_x) # (B*T, idea_dim) Q = Q.view(B*T, self.num_heads, self.head_dim) # (B*T, heads, head_dim)
# keys & values K = self.to_key(self.idea_pool) # (num_ideas, idea_dim) V = self.to_value(self.idea_pool) # (num_ideas, idea_dim) K = K.view(self.num_ideas, self.num_heads, self.head_dim).permute(1, 0, 2) V = V.view(self.num_ideas, self.num_heads, self.head_dim).permute(1, 0, 2)
# attention scores = torch.einsum("bhd,hkd->bhk", Q, K) / math.sqrt(self.head_dim) attn_weights = F.softmax(scores, dim=-1) # (B*T, heads, num_ideas) attn_out = torch.einsum("bhk,hkd->bhd", attn_weights, V) idea_vec = attn_out.reshape(B*T, -1) # (B*T, idea_dim)
# ββ SwiGLU FF upgrade ββ x_ff = self.ln(idea_vec) # RMSNorm x1, x2 = self.fc1(x_ff).chunk(2, dim=-1) # idea_dimβ2*idea_dim gated = F.silu(x1) * x2 # SiLU gate idea_vec = self.fc2(gated) # back to idea_dim
# project back & reshape out = self.out_proj(idea_vec).view(B, T, d)
stats = { "attn_weights": attn_weights.view(B, T, self.num_heads, -1).detach(), "idea_vector": idea_vec.view(B, T, -1).detach() } return out, stats
# ββ EmotionModule βββββββββββββββββββββββββββββββββββββββββββββββββββββββclass EmotionModule(nn.Module): def __init__(self, emotion_dim, embed_dim): super().__init__() self.proj = QuantLinear(emotion_dim, embed_dim, bias=True)
def forward(self, z, seq_len): z_proj = self.proj(z) return z_proj.unsqueeze(1).expand(-1, seq_len, -1)
# ββ Block ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββclass Block(nn.Module): def __init__(self, cfg: FreearchConfig): super().__init__() self.ln1 = RMSNorm(cfg.hidden_size) self.moe = MoE(cfg) self.ln2 = RMSNorm(cfg.hidden_size)
def forward(self, x): # Pre-normalization y = self.ln1(x) y = self.moe(y) # Residual connection + post-normalization return self.ln2(x + y)
# ββ Freearch ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββclass Freearch(nn.Module): def __init__(self, cfg: FreearchConfig): super().__init__() self.cfg = cfg self.token_emb = nn.Embedding(cfg.vocab_size, cfg.hidden_size) # Positional embeddings are learned parameters self.pos_emb = nn.Parameter(torch.zeros(1, cfg.max_seq_len, cfg.hidden_size)) self.emotion_mod = EmotionModule(cfg.emotion_dim, cfg.hidden_size) self.drop = nn.Dropout(0.1) # Stack of transformer blocks self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg.num_layers)]) self.ln_final = RMSNorm(cfg.hidden_size) self.brain = BrainModule(cfg.hidden_size, cfg.idea_dim, cfg.num_ideas) # Output layers self.lm_head = QuantLinear(cfg.hidden_size, cfg.vocab_size, bias=True) self.emotion_head = QuantLinear(cfg.hidden_size, cfg.emotion_dim, bias=True) self._init_weights()
def _init_weights(self): for m in self.modules(): if isinstance(m, (nn.Embedding, nn.Linear, QuantLinear)): nn.init.normal_(m.weight, mean=0.0, std=0.02) if hasattr(m, "bias") and m.bias is not None: nn.init.zeros_(m.bias) def forward(self, input_ids, emotions=None, use_generator=True): B, T = input_ids.shape assert T <= self.cfg.max_seq_len, \ f"Input sequence length {T} exceeds max_seq_len {self.cfg.max_seq_len}" x = self.token_emb(input_ids) + self.pos_emb[:, :T, :] if emotions is None: emotions = torch.zeros(B, self.cfg.emotion_dim, device=input_ids.device) x = x + self.emotion_mod(emotions, T)
x = self.drop(x) for block in self.blocks: x = block(x)
x = self.ln_final(x) x, brain_stats = self.brain(x, use_generator) logits = self.lm_head(x) pooled = x.mean(dim=1) emotion_pred = torch.tanh(self.emotion_head(pooled))
return logits, brain_stats, emotion_predmodel.pyDeleted-211