Run this model with HF Jobs
Run microsoft/phi-1 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/microsoft/phi-1. 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/microsoft/phi-1 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/microsoft/phi-1. 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/microsoft/phi-1. 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 microsoft/phi-1 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use microsoft/phi-1 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="microsoft/phi-1")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1") model = AutoModelForCausalLM.from_pretrained("microsoft/phi-1", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use microsoft/phi-1 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "microsoft/phi-1" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "microsoft/phi-1", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/microsoft/phi-1
- SGLang
How to use microsoft/phi-1 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 "microsoft/phi-1" \ --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": "microsoft/phi-1", "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 "microsoft/phi-1" \ --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": "microsoft/phi-1", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use microsoft/phi-1 with Docker Model Runner:
docker model run hf.co/microsoft/phi-1
fix(modeling_phi): Fixes cached generation when above maximum context length.
Browse files169 unmodified lines17017117217317417517617717817918080 unmodified lines261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292205 unmodified lines498499500501502503504505506357 unmodified lines864865866867868869870871872873874875876169 unmodified linesclass RotaryEmbedding(nn.Module):"""Rotary positional embedding (RoPE).Reference:RoFormer: Enhanced Transformer with Rotary Position Embedding.https://arxiv.org/pdf/2104.09864.pdf."""def __init__(80 unmodified linesseqlen_offset: int = 0,**kwargs,) -> Tuple[torch.Tensor, torch.Tensor]:seq_start = seqlen_offsetseq_end = seq_start + qkv.shape[1]if (self._cos_cached.device != qkv.deviceor self._cos_cached.dtype != qkv.dtypeor (self.training and self._cos_cached.is_inference())):self._update_cos_sin_cache(self.max_position_embeddings, device=qkv.device, dtype=qkv.dtype)if kv is None:return _apply_rotary_emb_qkv(qkv,self._cos_cached[seq_start:seq_end],self._sin_cached[seq_start:seq_end],)else:q = _apply_rotary_emb(qkv,self._cos_cached[seq_start:seq_end],self._sin_cached[seq_start:seq_end],)kv = _apply_rotary_emb_kv(kv,self._cos_cached[seq_start:seq_end],self._sin_cached[seq_start:seq_end],)return q, kv205 unmodified linessequence_end = sequence_start + kv.shape[1]# When the current sequence length is equal to or larger than the maximum sequence length,# we need to roll the cache to the left and update itif sequence_end >= inference_params.max_seqlen:inference_params.key_value_memory_dict[layer_idx] = inference_params.key_value_memory_dict[layer_idx].roll(-(sequence_end - sequence_start), 1)inference_params.key_value_memory_dict[layer_idx][batch_start:batch_end, sequence_start:sequence_end, ...] = kvkv = inference_params.key_value_memory_dict[layer_idx][batch_start:batch_end, :sequence_end, ...]357 unmodified linesattention_mask: Optional[Union[torch.LongTensor, torch.BoolTensor]] = None,**kwargs,) -> Dict[str, Any]:# Truncate `input_ids` and `attention_mask` (if necessary) to prevent exceeding# the maximum sequence lengthif input_ids.shape[1] > self.config.n_positions:input_ids = input_ids[:, -self.config.n_positions :]if attention_mask is not None:attention_mask = attention_mask[:, -self.config.n_positions :]if past_key_values is None or not (isinstance(past_key_values, InferenceParams)):past_key_values = InferenceParams(max_seqlen=self.config.n_positions,169 unmodified lines17017117217317417517617717817918080 unmodified lines261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290205 unmodified lines496497498499500501502503504357 unmodified lines862863864865866867169 unmodified linesclass RotaryEmbedding(nn.Module):"""Rotary positional embedding (RoPE).Reference:RoFormer: Enhanced Transformer with Rotary Position Embedding.https://arxiv.org/pdf/2104.09864.pdf."""def __init__(80 unmodified linesseqlen_offset: int = 0,**kwargs,) -> Tuple[torch.Tensor, torch.Tensor]:if (self._seq_len_cached < qkv.shape[1] + seqlen_offsetor self._cos_cached.device != qkv.deviceor self._cos_cached.dtype != qkv.dtypeor (self.training and self._cos_cached.is_inference())):self._update_cos_sin_cache(qkv.shape[1] + seqlen_offset, device=qkv.device, dtype=qkv.dtype)if kv is None:return _apply_rotary_emb_qkv(qkv,self._cos_cached[seqlen_offset:],self._sin_cached[seqlen_offset:],)else:q = _apply_rotary_emb(qkv,self._cos_cached[seqlen_offset:],self._sin_cached[seqlen_offset:],)kv = _apply_rotary_emb_kv(kv,self._cos_cached[seqlen_offset:],self._sin_cached[seqlen_offset:],)return q, kv205 unmodified linessequence_end = sequence_start + kv.shape[1]# When the current sequence length is equal to or larger than the maximum sequence length,# we need to concatenate the current `kv` with the cached `kv` to expand its lengthif sequence_end >= inference_params.max_seqlen:inference_params.key_value_memory_dict[layer_idx] = torch.concatenate((inference_params.key_value_memory_dict[layer_idx], kv), dim=1)inference_params.key_value_memory_dict[layer_idx][batch_start:batch_end, sequence_start:sequence_end, ...] = kvkv = inference_params.key_value_memory_dict[layer_idx][batch_start:batch_end, :sequence_end, ...]357 unmodified linesattention_mask: Optional[Union[torch.LongTensor, torch.BoolTensor]] = None,**kwargs,) -> Dict[str, Any]:if past_key_values is None or not (isinstance(past_key_values, InferenceParams)):past_key_values = InferenceParams(max_seqlen=self.config.n_positions,
modeling_phi.py+13-22