Instructions to use MedcellStudios/OLM3Nano with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use MedcellStudios/OLM3Nano with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="MedcellStudios/OLM3Nano", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("MedcellStudios/OLM3Nano", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use MedcellStudios/OLM3Nano with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "MedcellStudios/OLM3Nano" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "MedcellStudios/OLM3Nano", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/MedcellStudios/OLM3Nano
- SGLang
How to use MedcellStudios/OLM3Nano 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 "MedcellStudios/OLM3Nano" \ --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": "MedcellStudios/OLM3Nano", "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 "MedcellStudios/OLM3Nano" \ --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": "MedcellStudios/OLM3Nano", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use MedcellStudios/OLM3Nano with Docker Model Runner:
docker model run hf.co/MedcellStudios/OLM3Nano
Upload folder using huggingface_hub
Browse filesFiles changed (4)
- config.jsonAdded+26
- configuration_olm3nano.pyAdded+29
- model.safetensorsAdded+3
- modeling_olm3nano.pyAdded+368
1234567891011121314151617181920212223242526{ "architectures": [ "OLM3NanoForCausalLM" ], "model_type": "olm3_nano", "vocab_size": 50304, "hidden_size": 2048, "intermediate_size": 5504, "num_hidden_layers": 16, "num_attention_heads": 16, "max_position_embeddings": 2048, "rope_theta": 10000.0, "rms_norm_eps": 1e-05, "torch_dtype": "float32", "transformers_version": "custom", "auto_map": { "AutoConfig": "configuration_olm3nano.OLM3NanoConfig", "AutoModelForCausalLM": "modeling_olm3nano.OLM3NanoForCausalLM" }, "olm3_nano": { "checkpoint_step": 14086, "parameter_count": 1015613440, "training_corpus": "FineWeb" }, "tie_word_embeddings": true}1234567891011121314151617181920212223242526272829from transformers import PretrainedConfig
class OLM3NanoConfig(PretrainedConfig):
model_type = "olm3_nano"
def __init__( self, vocab_size=50304, hidden_size=2048, intermediate_size=5504, num_hidden_layers=16, num_attention_heads=16, max_position_embeddings=2048, rope_theta=10000.0, rms_norm_eps=1e-5, **kwargs ): super().__init__(**kwargs)
self.vocab_size = vocab_size self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.max_position_embeddings = max_position_embeddings self.rope_theta = rope_theta self.rms_norm_eps = rms_norm_eps123version https://git-lfs.github.com/spec/v1oid sha256:667211a84b721c4e411cfcfe28ffda51c87152a25e3ec47b39f49c24cabe2cc9size 4062465808123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368import torchimport torch.nn as nnimport torch.nn.functional as F
from transformers import PreTrainedModel, GenerationMixin, GenerationConfigfrom transformers.modeling_outputs import CausalLMOutput
from configuration_olm3nano import OLM3NanoConfig
class RMSNorm(nn.Module):
def __init__(self, dim, eps=1e-5): super().__init__()
self.weight = nn.Parameter( torch.ones(dim) )
self.eps = eps
def forward(self, x): return ( x * torch.rsqrt( x.pow(2).mean( -1, keepdim=True ) + self.eps ) * self.weight )
def precompute_rope( head_dim, max_seq_len, theta=10000.0):
freqs = 1.0 / ( theta ** ( torch.arange( 0, head_dim, 2, dtype=torch.float32 ) / head_dim ) )
t = torch.arange( max_seq_len, dtype=torch.float32 )
freqs = torch.outer(t, freqs)
return torch.cos(freqs), torch.sin(freqs)
def apply_rope(x, cos, sin):
x1 = x[..., 0::2] x2 = x[..., 1::2]
cos = cos[ :x.shape[-2] ].unsqueeze(0).unsqueeze(0)
sin = sin[ :x.shape[-2] ].unsqueeze(0).unsqueeze(0)
out1 = x1 * cos - x2 * sin out2 = x1 * sin + x2 * cos
return torch.stack( [out1, out2], dim=-1 ).flatten(-2)
class Attention(nn.Module):
def __init__(self, cfg): super().__init__()
self.n_head = cfg.num_attention_heads self.head_dim = ( cfg.hidden_size // cfg.num_attention_heads )
self.qkv = nn.Linear( cfg.hidden_size, 3 * cfg.hidden_size, bias=False )
self.proj = nn.Linear( cfg.hidden_size, cfg.hidden_size, bias=False )
def forward(self, x, cos, sin):
B, T, C = x.shape
qkv = self.qkv(x).view( B, T, 3, self.n_head, self.head_dim ).permute( 2, 0, 3, 1, 4 )
q, k, v = qkv
q = apply_rope(q, cos, sin) k = apply_rope(k, cos, sin)
out = F.scaled_dot_product_attention( q, k, v, is_causal=True )
out = ( out.transpose(1, 2) .contiguous() .view(B, T, C) )
return self.proj(out)
class SwiGLU(nn.Module):
def __init__(self, cfg): super().__init__()
self.w1 = nn.Linear( cfg.hidden_size, cfg.intermediate_size, bias=False )
self.w2 = nn.Linear( cfg.intermediate_size, cfg.hidden_size, bias=False )
self.w3 = nn.Linear( cfg.hidden_size, cfg.intermediate_size, bias=False )
def forward(self, x):
return self.w2( F.silu(self.w1(x)) * self.w3(x) )
class OLM3NanoBlock(nn.Module):
def __init__(self, cfg): super().__init__()
self.norm1 = RMSNorm( cfg.hidden_size, cfg.rms_norm_eps )
self.attn = Attention(cfg)
self.norm2 = RMSNorm( cfg.hidden_size, cfg.rms_norm_eps )
self.mlp = SwiGLU(cfg)
def forward(self, x, cos, sin):
x = x + self.attn( self.norm1(x), cos, sin )
x = x + self.mlp( self.norm2(x) )
return x
class OLM3NanoModel(nn.Module):
def __init__(self, cfg): super().__init__()
self.tok_emb = nn.Embedding( cfg.vocab_size, cfg.hidden_size )
self.blocks = nn.ModuleList([ OLM3NanoBlock(cfg) for _ in range( cfg.num_hidden_layers ) ])
self.norm_f = RMSNorm( cfg.hidden_size, cfg.rms_norm_eps )
head_dim = ( cfg.hidden_size // cfg.num_attention_heads )
cos, sin = precompute_rope( head_dim, cfg.max_position_embeddings, cfg.rope_theta )
self.register_buffer( "rope_cos", cos, persistent=False )
self.register_buffer( "rope_sin", sin, persistent=False ) self._rope_head_dim = head_dim self._rope_max_seq_len = cfg.max_position_embeddings self._rope_theta = cfg.rope_theta
def forward(self, input_ids):
x = self.tok_emb(input_ids)
# RECOMPUTE_ROPE_EACH_FORWARD: guarantees correct rope buffers # regardless of how the model was constructed/loaded (works around # persistent=False buffers getting corrupted by from_pretrained's # meta-device -> real-device migration for missing keys). _cos, _sin = precompute_rope( self._rope_head_dim, self._rope_max_seq_len, self._rope_theta, ) self.rope_cos.data = _cos.to(x.device, x.dtype) self.rope_sin.data = _sin.to(x.device, x.dtype)
for block in self.blocks: x = block( x, self.rope_cos, self.rope_sin )
return self.norm_f(x)
class OLM3NanoForCausalLM( PreTrainedModel, GenerationMixin):
config_class = OLM3NanoConfig
def __init__(self, config):
super().__init__(config)
self.model = OLM3NanoModel( config )
self.lm_head = nn.Linear( config.hidden_size, config.vocab_size, bias=False )
self.post_init() self.generation_config = GenerationConfig()
# Recompute RoPE buffers post-init: with some transformers versions, # persistent=False buffers loaded via from_pretrained can end up as # uninitialized/garbage memory instead of the values computed in # OLM3NanoModel.__init__. Force a clean recompute here as a guarantee. _head_dim = config.hidden_size // config.num_attention_heads _cos, _sin = precompute_rope( _head_dim, config.max_position_embeddings, config.rope_theta, ) self.model.rope_cos.data = _cos.to( self.model.rope_cos.device, self.model.rope_cos.dtype ) self.model.rope_sin.data = _sin.to( self.model.rope_sin.device, self.model.rope_sin.dtype )
def can_generate(self): return True
def prepare_inputs_for_generation(self, input_ids, **kwargs): return {"input_ids": input_ids}
def forward( self, input_ids=None, labels=None, **kwargs ):
hidden = self.model( input_ids )
logits = self.lm_head( hidden )
loss = None
if labels is not None:
shift_logits = logits[ ..., :-1, : ].contiguous()
shift_labels = labels[ ..., 1: ].contiguous()
loss = F.cross_entropy( shift_logits.view( -1, shift_logits.size(-1) ), shift_labels.view(-1) )
return CausalLMOutput( loss=loss, logits=logits )config.jsonAdded+26
configuration_olm3nano.pyAdded+29
model.safetensorsAdded+3
modeling_olm3nano.pyAdded+368