Run this model with HF Jobs
Run tiny-random/phi-moe 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/tiny-random/phi-moe. 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/tiny-random/phi-moe 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/tiny-random/phi-moe. 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/tiny-random/phi-moe. 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 tiny-random/phi-moe with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use tiny-random/phi-moe with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="tiny-random/phi-moe", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("tiny-random/phi-moe", trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained("tiny-random/phi-moe", trust_remote_code=True, device_map="auto") messages = [ {"role": "user", "content": "Who are you?"}, ] inputs = tokenizer.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use tiny-random/phi-moe with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "tiny-random/phi-moe" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "tiny-random/phi-moe", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/tiny-random/phi-moe
- SGLang
How to use tiny-random/phi-moe 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 "tiny-random/phi-moe" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "tiny-random/phi-moe", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'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 "tiny-random/phi-moe" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "tiny-random/phi-moe", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use tiny-random/phi-moe with Docker Model Runner:
docker model run hf.co/tiny-random/phi-moe
Upload folder using huggingface_hub
Browse filesFiles changed (7)
- README.mdAdded+142
- config.jsonAdded+41
- generation_config.jsonAdded+11
- model.safetensorsAdded+3
- special_tokens_map.jsonAdded+30
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded+132
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142---library_name: transformerspipeline_tag: text-generationinference: truewidget: - text: Hello! example_title: Hello world group: Pythonbase_model:- microsoft/Phi-tiny-MoE-instruct---
This tiny model is for debugging. It is randomly initialized with the config adapted from [microsoft/Phi-tiny-MoE-instruct](https://huggingface.co/microsoft/Phi-tiny-MoE-instruct).
### Example usage:
```pythonimport torch
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
model_id = "tiny-random/phi-moe"tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained( model_id, torch_dtype=torch.bfloat16, trust_remote_code=True,)pipe = pipeline('text-generation', model=model, tokenizer=tokenizer, trust_remote_code=True)print(pipe('Write an article about Artificial Intelligence.'))```
### Codes to create this repo:
```pythonimport jsonfrom pathlib import Path
import torch
import acceleratefrom huggingface_hub import file_exists, hf_hub_downloadfrom transformers import ( AutoConfig, AutoModelForCausalLM, AutoTokenizer, GenerationConfig, set_seed,)
source_model_id = "microsoft/Phi-tiny-MoE-instruct"save_folder = "/tmp/tiny-random/phi-moe"
processor = AutoTokenizer.from_pretrained(source_model_id)processor.save_pretrained(save_folder)
with open(hf_hub_download(source_model_id, filename='config.json', repo_type='model'), 'r', encoding='utf-8') as f: config_json = json.load(f)
for k, v in config_json['auto_map'].items(): config_json['auto_map'][k] = f'{source_model_id}--{v}'config_json['head_dim'] = 32config_json['hidden_size'] = 64config_json['intermediate_size'] = 128config_json['num_attention_heads'] = 2config_json['num_experts_per_tok'] = 2config_json['num_hidden_layers'] = 2config_json['num_key_value_heads'] = 1config_json['num_local_experts'] = 8config_json['tie_word_embeddings'] = True
with open(f"{save_folder}/config.json", "w", encoding='utf-8') as f: json.dump(config_json, f, indent=2)
config = AutoConfig.from_pretrained( save_folder, trust_remote_code=True,)print(config)automap = config_json['auto_map']torch.set_default_dtype(torch.bfloat16)model = AutoModelForCausalLM.from_config(config, trust_remote_code=True)torch.set_default_dtype(torch.float32)# according to source model, gat is in FP32for i in range(config.num_hidden_layers): model.model.layers[i].block_sparse_moe.gate.float()if file_exists(filename="generation_config.json", repo_id=source_model_id, repo_type='model'): model.generation_config = GenerationConfig.from_pretrained( source_model_id, trust_remote_code=True, )set_seed(42)model = model.cpu() # cpu is more stable for random initialization across machineswith torch.no_grad(): for name, p in sorted(model.named_parameters()): torch.nn.init.normal_(p, 0, 0.2) print(name, p.shape)model.save_pretrained(save_folder)print(model)with open(f"{save_folder}/config.json", "r", encoding='utf-8') as f: config_json = json.load(f) config_json['auto_map'] = automapwith open(f"{save_folder}/config.json", "w", encoding='utf-8') as f: json.dump(config_json, f, indent=2)for python_file in Path(save_folder).glob('*.py'): python_file.unlink()```
### Printing the model:
```textPhiMoEForCausalLM( (model): PhiMoEModel( (embed_tokens): Embedding(32064, 64) (layers): ModuleList( (0-1): 2 x PhiMoEDecoderLayer( (self_attn): PhiMoESdpaAttention( (q_proj): Linear(in_features=64, out_features=64, bias=True) (k_proj): Linear(in_features=64, out_features=32, bias=True) (v_proj): Linear(in_features=64, out_features=32, bias=True) (o_proj): Linear(in_features=64, out_features=64, bias=True) (rotary_emb): PhiMoERotaryEmbedding() ) (block_sparse_moe): PhiMoESparseMoeBlock( (gate): Linear(in_features=64, out_features=8, bias=False) (experts): ModuleList( (0-7): 8 x PhiMoEBlockSparseTop2MLP( (w1): Linear(in_features=64, out_features=128, bias=False) (w2): Linear(in_features=128, out_features=64, bias=False) (w3): Linear(in_features=64, out_features=128, bias=False) (act_fn): SiLU() ) ) ) (input_layernorm): LayerNorm((64,), eps=1e-05, elementwise_affine=True) (post_attention_layernorm): LayerNorm((64,), eps=1e-05, elementwise_affine=True) ) ) (norm): LayerNorm((64,), eps=1e-05, elementwise_affine=True) ) (lm_head): Linear(in_features=64, out_features=32064, bias=True))```1234567891011121314151617181920212223242526272829303132333435363738394041{ "architectures": [ "PhiMoEForCausalLM" ], "attention_bias": true, "attention_dropout": 0.0, "auto_map": { "AutoConfig": "microsoft/Phi-tiny-MoE-instruct--configuration_slimmoe.PhiMoEConfig", "AutoModelForCausalLM": "microsoft/Phi-tiny-MoE-instruct--modeling_slimmoe.PhiMoEForCausalLM" }, "bos_token_id": 1, "eos_token_id": 32000, "expert_dropout": 0.0, "head_dim": 32, "hidden_act": "silu", "hidden_dropout": 0.0, "hidden_size": 64, "initializer_range": 0.02, "input_jitter_noise": 0.01, "intermediate_size": 128, "lm_head_bias": true, "max_position_embeddings": 4096, "model_type": "phimoe", "num_attention_heads": 2, "num_experts_per_tok": 2, "num_hidden_layers": 2, "num_key_value_heads": 1, "num_local_experts": 8, "output_router_logits": false, "rms_norm_eps": 1e-05, "rope_scaling": null, "rope_theta": 10000.0, "router_aux_loss_coef": 0.0, "router_jitter_noise": 0.01, "sliding_window": 2047, "tie_word_embeddings": true, "torch_dtype": "bfloat16", "transformers_version": "4.51.3", "use_cache": true, "vocab_size": 32064}1234567891011{ "_from_model_config": true, "bos_token_id": 1, "eos_token_id": [ 32000, 32001, 32007 ], "pad_token_id": 32000, "transformers_version": "4.51.3"}123version https://git-lfs.github.com/spec/v1oid sha256:bdf2f1fe515fa0b55cc3be523a7e19a36d27053254bfcdf6f0ecada43c393bcdsize 5018960123456789101112131415161718192021222324252627282930{ "bos_token": { "content": "<s>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "eos_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "unk_token": { "content": "<unk>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132{ "add_bos_token": false, "add_eos_token": false, "add_prefix_space": null, "added_tokens_decoder": { "0": { "content": "<unk>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "1": { "content": "<s>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "2": { "content": "</s>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": false }, "32000": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32001": { "content": "<|assistant|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "32002": { "content": "<|placeholder1|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "32003": { "content": "<|placeholder2|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "32004": { "content": "<|placeholder3|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "32005": { "content": "<|placeholder4|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "32006": { "content": "<|system|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "32007": { "content": "<|end|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "32008": { "content": "<|placeholder5|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "32009": { "content": "<|placeholder6|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true }, "32010": { "content": "<|user|>", "lstrip": false, "normalized": false, "rstrip": true, "single_word": false, "special": true } }, "bos_token": "<s>", "chat_template": "{% for message in messages %}{{'<|' + message['role'] + '|>' + '\n' + message['content'] + '<|end|>\n' }}{% endfor %}{% if add_generation_prompt %}{{ '<|assistant|>\n' }}{% else %}{{ eos_token }}{% endif %}", "clean_up_tokenization_spaces": false, "eos_token": "<|endoftext|>", "extra_special_tokens": {}, "legacy": false, "model_max_length": 4096, "pad_token": "<|endoftext|>", "padding_side": "left", "sp_model_kwargs": {}, "tokenizer_class": "LlamaTokenizerFast", "unk_token": "<unk>", "use_default_system_prompt": false}README.mdAdded+142
config.jsonAdded+41
generation_config.jsonAdded+11
model.safetensorsAdded+3
special_tokens_map.jsonAdded+30
tokenizer.jsonAdded
tokenizer_config.jsonAdded+132