Setup repo with Phi 3
This commit is contained in:
49
.github/workflows/download.yml
vendored
Normal file
49
.github/workflows/download.yml
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
name: Download Missing Models
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
paths:
|
||||
- 'models/**/model.yaml'
|
||||
- 'tools/download.sh'
|
||||
|
||||
jobs:
|
||||
download-models:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
lfs: true
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.x'
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pip install pyyaml huggingface_hub yq
|
||||
|
||||
- name: Make scripts executable
|
||||
run: chmod +x tools/download.sh
|
||||
|
||||
- name: Download missing models
|
||||
run: |
|
||||
for yaml in $(find models -name model.yaml); do
|
||||
echo "Processing $yaml"
|
||||
./tools/download.sh "$yaml"
|
||||
done
|
||||
|
||||
- name: Commit and push downloaded models
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git add models
|
||||
if git diff --cached --quiet; then
|
||||
echo "No new files to commit."
|
||||
else
|
||||
git commit -m "Add downloaded model files"
|
||||
git push
|
||||
fi
|
||||
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
.idea
|
||||
21
LICENSE
Normal file
21
LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 Worka AI
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
77
README.md
Normal file
77
README.md
Normal file
@@ -0,0 +1,77 @@
|
||||
# Worka Models Repository
|
||||
|
||||
This repository contains **Candle-supported, redistributable, community-quantized models**
|
||||
(primarily in **GGUF** and **safetensors** formats) ready for use in [Worka](https://github.com/your-org/worka).
|
||||
|
||||
## 📂 Repository Structure
|
||||
|
||||
```
|
||||
models/
|
||||
llama-2-7b/
|
||||
README.md # Original Hugging Face model card content
|
||||
model.yaml # Machine-readable metadata (formats, quantizations, files)
|
||||
quantized/ # GGUF quantized weights
|
||||
safetensors/ # Float16 safetensor weights
|
||||
tokenizer/ # Tokenizer files
|
||||
tools/
|
||||
download.sh # Script to fetch missing models from Hugging Face
|
||||
verify-checksums.py # Verify downloaded files against known hashes
|
||||
generate-registry.py # Generate registry.json from all model.yaml files
|
||||
.gitattributes # Configure Git LFS
|
||||
.github/workflows/download.yml # GitHub Action to fetch models automatically
|
||||
```
|
||||
|
||||
## 🧩 Metadata Format (`model.yaml`)
|
||||
|
||||
Each model has a `model.yaml` file describing:
|
||||
|
||||
- **Model name & description**
|
||||
- **Publisher attribution**:
|
||||
- *Original unquantized model publisher* (e.g., Meta for LLaMA)
|
||||
- *Quantization publisher* (e.g., TheBloke)
|
||||
- **Available formats** (`gguf`, `safetensors`)
|
||||
- **Quantization variants** (with user-friendly labels, file lists, download size)
|
||||
- **Tokenizer files**
|
||||
- **VRAM requirements**
|
||||
|
||||
This YAML is used by Worka to present model options and to **sparse-checkout** only the required files.
|
||||
|
||||
## 🚀 Using Sparse Checkout
|
||||
|
||||
You can fetch only the files for the model/quantization you need:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/your-org/worka-models.git
|
||||
cd worka-models
|
||||
|
||||
# Enable sparse checkout
|
||||
git sparse-checkout init --cone
|
||||
|
||||
# Set which model files to fetch (example: LLaMA 2 7B Q4_K_M)
|
||||
git sparse-checkout set models/llama-2-7b/quantized/llama-2-7b.Q4_K_M.gguf models/llama-2-7b/tokenizer/tokenizer.model models/llama-2-7b/model.yaml
|
||||
```
|
||||
|
||||
## 🛠 Helper Scripts
|
||||
|
||||
- **`tools/download.sh`** – Fetches missing models from Hugging Face using metadata in `model.yaml`.
|
||||
- **`tools/verify-checksums.py`** – Verifies downloaded files against stored hashes.
|
||||
- **`tools/generate-registry.py`** – Generates a consolidated `registry.json` from all YAMLs.
|
||||
|
||||
## 🤖 GitHub Actions
|
||||
|
||||
A workflow in `.github/workflows/download.yml` runs `download.sh` to fetch any configured model missing from the repo.
|
||||
|
||||
## 📜 License & Attribution
|
||||
|
||||
All models are redistributed under their respective licenses.
|
||||
Each `model.yaml` file carries **attribution** for both:
|
||||
- **Original unquantized publisher**
|
||||
- **Quantized publisher**
|
||||
|
||||
## ⚠️ Notes
|
||||
|
||||
- Only **ungated, redistributable** models are included.
|
||||
- **We do not include** gated models like unquantized LLaMA weights from Meta — these must be fetched by the user directly.
|
||||
|
||||
---
|
||||
For details about individual models, see their `README.md` inside each `models/<model-name>/` folder.
|
||||
22
models/Phi-3-mini-128k-instruct/LICENSE
Normal file
22
models/Phi-3-mini-128k-instruct/LICENSE
Normal file
@@ -0,0 +1,22 @@
|
||||
Microsoft.
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
346
models/Phi-3-mini-128k-instruct/README.md
Normal file
346
models/Phi-3-mini-128k-instruct/README.md
Normal file
@@ -0,0 +1,346 @@
|
||||
---
|
||||
license: mit
|
||||
license_link: https://huggingface.co/microsoft/Phi-3-mini-128k-instruct/resolve/main/LICENSE
|
||||
|
||||
language:
|
||||
- en
|
||||
pipeline_tag: text-generation
|
||||
tags:
|
||||
- nlp
|
||||
- code
|
||||
widget:
|
||||
- messages:
|
||||
- role: user
|
||||
content: Can you provide ways to eat combinations of bananas and dragonfruits?
|
||||
---
|
||||
🎉**Phi-4**: [[multimodal-instruct](https://huggingface.co/microsoft/Phi-4-multimodal-instruct) | [onnx](https://huggingface.co/microsoft/Phi-4-multimodal-instruct-onnx)];
|
||||
[[mini-instruct](https://huggingface.co/microsoft/Phi-4-mini-instruct) | [onnx](https://huggingface.co/microsoft/Phi-4-mini-instruct-onnx)]
|
||||
|
||||
## Model Summary
|
||||
|
||||
The Phi-3-Mini-128K-Instruct is a 3.8 billion-parameter, lightweight, state-of-the-art open model trained using the Phi-3 datasets.
|
||||
This dataset includes both synthetic data and filtered publicly available website data, with an emphasis on high-quality and reasoning-dense properties.
|
||||
The model belongs to the Phi-3 family with the Mini version in two variants [4K](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct) and [128K](https://huggingface.co/microsoft/Phi-3-mini-128k-instruct) which is the context length (in tokens) that it can support.
|
||||
|
||||
After initial training, the model underwent a post-training process that involved supervised fine-tuning and direct preference optimization to enhance its ability to follow instructions and adhere to safety measures.
|
||||
When evaluated against benchmarks that test common sense, language understanding, mathematics, coding, long-term context, and logical reasoning, the Phi-3 Mini-128K-Instruct demonstrated robust and state-of-the-art performance among models with fewer than 13 billion parameters.
|
||||
Resources and Technical Documentation:
|
||||
|
||||
🏡 [Phi-3 Portal](https://azure.microsoft.com/en-us/products/phi-3) <br>
|
||||
📰 [Phi-3 Microsoft Blog](https://aka.ms/Phi-3Build2024) <br>
|
||||
📖 [Phi-3 Technical Report](https://aka.ms/phi3-tech-report) <br>
|
||||
🛠️ [Phi-3 on Azure AI Studio](https://aka.ms/phi3-azure-ai) <br>
|
||||
👩🍳 [Phi-3 Cookbook](https://github.com/microsoft/Phi-3CookBook) <br>
|
||||
🖥️ [Try It](https://aka.ms/try-phi3)
|
||||
|
||||
| | Short Context | Long Context |
|
||||
| :- | :- | :- |
|
||||
| Mini | 4K [[HF]](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct) ; [[ONNX]](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-onnx) ; [[GGUF]](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-gguf) | 128K [[HF]](https://huggingface.co/microsoft/Phi-3-mini-128k-instruct) ; [[ONNX]](https://huggingface.co/microsoft/Phi-3-mini-128k-instruct-onnx)|
|
||||
| Small | 8K [[HF]](https://huggingface.co/microsoft/Phi-3-small-8k-instruct) ; [[ONNX]](https://huggingface.co/microsoft/Phi-3-small-8k-instruct-onnx-cuda) | 128K [[HF]](https://huggingface.co/microsoft/Phi-3-small-128k-instruct) ; [[ONNX]](https://huggingface.co/microsoft/Phi-3-small-128k-instruct-onnx-cuda)|
|
||||
| Medium | 4K [[HF]](https://huggingface.co/microsoft/Phi-3-medium-4k-instruct) ; [[ONNX]](https://huggingface.co/microsoft/Phi-3-medium-4k-instruct-onnx-cuda) | 128K [[HF]](https://huggingface.co/microsoft/Phi-3-medium-128k-instruct) ; [[ONNX]](https://huggingface.co/microsoft/Phi-3-medium-128k-instruct-onnx-cuda)|
|
||||
| Vision | | 128K [[HF]](https://huggingface.co/microsoft/Phi-3-vision-128k-instruct) ; [[ONNX]](https://huggingface.co/microsoft/Phi-3-vision-128k-instruct-onnx-cuda)|
|
||||
|
||||
|
||||
|
||||
## Intended Uses
|
||||
|
||||
**Primary use cases**
|
||||
|
||||
The model is intended for commercial and research use in English. The model provides uses for applications which require:
|
||||
|
||||
1) Memory/compute constrained environments
|
||||
2) Latency bound scenarios
|
||||
3) Strong reasoning (especially code, math and logic)
|
||||
|
||||
Our model is designed to accelerate research on language and multimodal models, for use as a building block for generative AI powered features.
|
||||
|
||||
**Use case considerations**
|
||||
|
||||
Our models are not specifically designed or evaluated for all downstream purposes. Developers should consider common limitations of language models as they select use cases, and evaluate and mitigate for accuracy, safety, and fariness before using within a specific downstream use case, particularly for high risk scenarios. Developers should be aware of and adhere to applicable laws or regulations (including privacy, trade compliance laws, etc.) that are relevant to their use case.
|
||||
|
||||
Nothing contained in this Model Card should be interpreted as or deemed a restriction or modification to the license the model is released under.
|
||||
|
||||
## Release Notes
|
||||
|
||||
This is an update over the original instruction-tuned Phi-3-mini release based on valuable customer feedback.
|
||||
The model used additional post-training data leading to substantial gains on long-context understanding, instruction following, and structure output.
|
||||
We also improve multi-turn conversation quality, explicitly support <|system|> tag, and significantly improve reasoning capability.
|
||||
We believe most use cases will benefit from this release, but we encourage users to test in their particular AI applications.
|
||||
We appreciate the enthusiastic adoption of the Phi-3 model family, and continue to welcome all feedback from the community.
|
||||
|
||||
These tables below highlights improvements on instruction following, structure output, reasoning, and long-context understanding of the new release on our public and internal benchmark datasets.
|
||||
|
||||
| Benchmarks | Original | June 2024 Update |
|
||||
| :- | :- | :- |
|
||||
| Instruction Extra Hard | 5.7 | 5.9 |
|
||||
| Instruction Hard | 5.0 | 5.2 |
|
||||
| JSON Structure Output | 1.9 | 60.1 |
|
||||
| XML Structure Output | 47.8 | 52.9 |
|
||||
| GPQA | 25.9 | 29.7 |
|
||||
| MMLU | 68.1 | 69.7 |
|
||||
| **Average** | **25.7** | **37.3** |
|
||||
|
||||
RULER: a retrieval-based benchmark for long context understanding
|
||||
|
||||
| Model | 4K | 8K | 16K | 32K | 64K | 128K | Average |
|
||||
| :-------------------| :------| :------| :------| :------| :------| :------| :---------|
|
||||
| Original | 86.7 | 78.1 | 75.6 | 70.3 | 58.9 | 43.3 | **68.8** |
|
||||
| June 2024 Update | 92.4 | 91.1 | 90.8 | 87.9 | 79.8 | 65.6 | **84.6** |
|
||||
|
||||
RepoQA: a benchmark for long context code understanding
|
||||
|
||||
| Model | Python | C++ | Rust | Java | TypeScript | Average |
|
||||
| :-------------------| :--------| :-----| :------| :------| :------------| :---------|
|
||||
| Original | 27 | 29 | 40 | 33 | 33 | **32.4** |
|
||||
| June 2024 Update | 85 | 63 | 72 | 93 | 72 | **77** |
|
||||
|
||||
|
||||
Notes: if users would like to check out the previous version, use the git commit id **bb5bf1e4001277a606e11debca0ef80323e5f824**. For the model conversion, e.g. GGUF and other formats, we invite the community to experiment with various approaches and share your valuable feedback. Let's innovate together!
|
||||
|
||||
## How to Use
|
||||
|
||||
Phi-3 Mini-128K-Instruct has been integrated in the development version (4.41.3) of `transformers`. Until the official version is released through `pip`, ensure that you are doing one of the following:
|
||||
|
||||
* When loading the model, ensure that `trust_remote_code=True` is passed as an argument of the `from_pretrained()` function.
|
||||
|
||||
* Update your local `transformers` to the development version: `pip uninstall -y transformers && pip install git+https://github.com/huggingface/transformers`. The previous command is an alternative to cloning and installing from the source.
|
||||
|
||||
The current `transformers` version can be verified with: `pip list | grep transformers`.
|
||||
|
||||
Examples of required packages:
|
||||
```
|
||||
flash_attn==2.5.8
|
||||
torch==2.3.1
|
||||
accelerate==0.31.0
|
||||
transformers==4.41.2
|
||||
```
|
||||
|
||||
Phi-3 Mini-128K-Instruct is also available in [Azure AI Studio](https://aka.ms/try-phi3)
|
||||
|
||||
### Tokenizer
|
||||
|
||||
Phi-3 Mini-128K-Instruct supports a vocabulary size of up to `32064` tokens. The [tokenizer files](https://huggingface.co/microsoft/Phi-3-mini-128k-instruct/blob/main/added_tokens.json) already provide placeholder tokens that can be used for downstream fine-tuning, but they can also be extended up to the model's vocabulary size.
|
||||
|
||||
|
||||
### Chat Format
|
||||
|
||||
Given the nature of the training data, the Phi-3 Mini-128K-Instruct model is best suited for prompts using the chat format as follows.
|
||||
You can provide the prompt as a question with a generic template as follow:
|
||||
```markdown
|
||||
<|system|>
|
||||
You are a helpful assistant.<|end|>
|
||||
<|user|>
|
||||
Question?<|end|>
|
||||
<|assistant|>
|
||||
```
|
||||
|
||||
For example:
|
||||
```markdown
|
||||
<|system|>
|
||||
You are a helpful assistant.<|end|>
|
||||
<|user|>
|
||||
How to explain Internet for a medieval knight?<|end|>
|
||||
<|assistant|>
|
||||
```
|
||||
where the model generates the text after `<|assistant|>` . In case of few-shots prompt, the prompt can be formatted as the following:
|
||||
|
||||
```markdown
|
||||
<|system|>
|
||||
You are a helpful travel assistant.<|end|>
|
||||
<|user|>
|
||||
I am going to Paris, what should I see?<|end|>
|
||||
<|assistant|>
|
||||
Paris, the capital of France, is known for its stunning architecture, art museums, historical landmarks, and romantic atmosphere. Here are some of the top attractions to see in Paris:\n\n1. The Eiffel Tower: The iconic Eiffel Tower is one of the most recognizable landmarks in the world and offers breathtaking views of the city.\n2. The Louvre Museum: The Louvre is one of the world's largest and most famous museums, housing an impressive collection of art and artifacts, including the Mona Lisa.\n3. Notre-Dame Cathedral: This beautiful cathedral is one of the most famous landmarks in Paris and is known for its Gothic architecture and stunning stained glass windows.\n\nThese are just a few of the many attractions that Paris has to offer. With so much to see and do, it's no wonder that Paris is one of the most popular tourist destinations in the world."<|end|>
|
||||
<|user|>
|
||||
What is so great about #1?<|end|>
|
||||
<|assistant|>
|
||||
```
|
||||
|
||||
### Sample inference code
|
||||
|
||||
This code snippets show how to get quickly started with running the model on a GPU:
|
||||
|
||||
```python
|
||||
import torch
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
||||
|
||||
torch.random.manual_seed(0)
|
||||
model = AutoModelForCausalLM.from_pretrained(
|
||||
"microsoft/Phi-3-mini-128k-instruct",
|
||||
device_map="cuda",
|
||||
torch_dtype="auto",
|
||||
trust_remote_code=True,
|
||||
)
|
||||
|
||||
tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-128k-instruct")
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": "You are a helpful AI assistant."},
|
||||
{"role": "user", "content": "Can you provide ways to eat combinations of bananas and dragonfruits?"},
|
||||
{"role": "assistant", "content": "Sure! Here are some ways to eat bananas and dragonfruits together: 1. Banana and dragonfruit smoothie: Blend bananas and dragonfruits together with some milk and honey. 2. Banana and dragonfruit salad: Mix sliced bananas and dragonfruits together with some lemon juice and honey."},
|
||||
{"role": "user", "content": "What about solving an 2x + 3 = 7 equation?"},
|
||||
]
|
||||
|
||||
pipe = pipeline(
|
||||
"text-generation",
|
||||
model=model,
|
||||
tokenizer=tokenizer,
|
||||
)
|
||||
|
||||
generation_args = {
|
||||
"max_new_tokens": 500,
|
||||
"return_full_text": False,
|
||||
"temperature": 0.0,
|
||||
"do_sample": False,
|
||||
}
|
||||
|
||||
output = pipe(messages, **generation_args)
|
||||
print(output[0]['generated_text'])
|
||||
```
|
||||
|
||||
Notes: If you want to use flash attention, call _AutoModelForCausalLM.from_pretrained()_ with _attn_implementation="flash_attention_2"_
|
||||
|
||||
## Responsible AI Considerations
|
||||
|
||||
Like other language models, the Phi series models can potentially behave in ways that are unfair, unreliable, or offensive. Some of the limiting behaviors to be aware of include:
|
||||
|
||||
+ Quality of Service: the Phi models are trained primarily on English text. Languages other than English will experience worse performance. English language varieties with less representation in the training data might experience worse performance than standard American English.
|
||||
+ Representation of Harms & Perpetuation of Stereotypes: These models can over- or under-represent groups of people, erase representation of some groups, or reinforce demeaning or negative stereotypes. Despite safety post-training, these limitations may still be present due to differing levels of representation of different groups or prevalence of examples of negative stereotypes in training data that reflect real-world patterns and societal biases.
|
||||
+ Inappropriate or Offensive Content: these models may produce other types of inappropriate or offensive content, which may make it inappropriate to deploy for sensitive contexts without additional mitigations that are specific to the use case.
|
||||
+ Information Reliability: Language models can generate nonsensical content or fabricate content that might sound reasonable but is inaccurate or outdated.
|
||||
+ Limited Scope for Code: Majority of Phi-3 training data is based in Python and use common packages such as "typing, math, random, collections, datetime, itertools". If the model generates Python scripts that utilize other packages or scripts in other languages, we strongly recommend users manually verify all API uses.
|
||||
|
||||
Developers should apply responsible AI best practices and are responsible for ensuring that a specific use case complies with relevant laws and regulations (e.g. privacy, trade, etc.). Important areas for consideration include:
|
||||
|
||||
+ Allocation: Models may not be suitable for scenarios that could have consequential impact on legal status or the allocation of resources or life opportunities (ex: housing, employment, credit, etc.) without further assessments and additional debiasing techniques.
|
||||
+ High-Risk Scenarios: Developers should assess suitability of using models in high-risk scenarios where unfair, unreliable or offensive outputs might be extremely costly or lead to harm. This includes providing advice in sensitive or expert domains where accuracy and reliability are critical (ex: legal or health advice). Additional safeguards should be implemented at the application level according to the deployment context.
|
||||
+ Misinformation: Models may produce inaccurate information. Developers should follow transparency best practices and inform end-users they are interacting with an AI system. At the application level, developers can build feedback mechanisms and pipelines to ground responses in use-case specific, contextual information, a technique known as Retrieval Augmented Generation (RAG).
|
||||
+ Generation of Harmful Content: Developers should assess outputs for their context and use available safety classifiers or custom solutions appropriate for their use case.
|
||||
+ Misuse: Other forms of misuse such as fraud, spam, or malware production may be possible, and developers should ensure that their applications do not violate applicable laws and regulations.
|
||||
|
||||
## Training
|
||||
|
||||
### Model
|
||||
|
||||
* Architecture: Phi-3 Mini-128K-Instruct has 3.8B parameters and is a dense decoder-only Transformer model. The model is fine-tuned with Supervised fine-tuning (SFT) and Direct Preference Optimization (DPO) to ensure alignment with human preferences and safety guidlines.
|
||||
* Inputs: Text. It is best suited for prompts using chat format.
|
||||
* Context length: 128K tokens
|
||||
* GPUs: 512 H100-80G
|
||||
* Training time: 10 days
|
||||
* Training data: 4.9T tokens
|
||||
* Outputs: Generated text in response to the input
|
||||
* Dates: Our models were trained between May and June 2024
|
||||
* Status: This is a static model trained on an offline dataset with cutoff date October 2023. Future versions of the tuned models may be released as we improve models.
|
||||
* Release dates: June, 2024.
|
||||
|
||||
### Datasets
|
||||
|
||||
Our training data includes a wide variety of sources, totaling 4.9 trillion tokens, and is a combination of
|
||||
1) Publicly available documents filtered rigorously for quality, selected high-quality educational data, and code;
|
||||
2) Newly created synthetic, “textbook-like” data for the purpose of teaching math, coding, common sense reasoning, general knowledge of the world (science, daily activities, theory of mind, etc.);
|
||||
3) High quality chat format supervised data covering various topics to reflect human preferences on different aspects such as instruct-following, truthfulness, honesty and helpfulness.
|
||||
|
||||
We are focusing on the quality of data that could potentially improve the reasoning ability for the model, and we filter the publicly available documents to contain the correct level of knowledge. As an example, the result of a game in premier league in a particular day might be good training data for frontier models, but we need to remove such information to leave more model capacity for reasoning for the small size models. More details about data can be found in the [Phi-3 Technical Report](https://aka.ms/phi3-tech-report).
|
||||
|
||||
### Fine-tuning
|
||||
|
||||
A basic example of multi-GPUs supervised fine-tuning (SFT) with TRL and Accelerate modules is provided [here](https://huggingface.co/microsoft/Phi-3-mini-128k-instruct/resolve/main/sample_finetune.py).
|
||||
|
||||
## Benchmarks
|
||||
|
||||
We report the results under completion format for Phi-3-Mini-128K-Instruct on standard open-source benchmarks measuring the model's reasoning ability (both common sense reasoning and logical reasoning). We compare to Mistral-7b-v0.1, Mixtral-8x7b, Gemma 7B, Llama-3-8B-Instruct, and GPT-3.5.
|
||||
|
||||
All the reported numbers are produced with the exact same pipeline to ensure that the numbers are comparable. These numbers might differ from other published numbers due to slightly different choices in the evaluation.
|
||||
|
||||
As is now standard, we use few-shot prompts to evaluate the models, at temperature 0.
|
||||
The prompts and number of shots are part of a Microsoft internal tool to evaluate language models, and in particular we did no optimization to the pipeline for Phi-3.
|
||||
More specifically, we do not change prompts, pick different few-shot examples, change prompt format, or do any other form of optimization for the model.
|
||||
|
||||
The number of k–shot examples is listed per-benchmark.
|
||||
|
||||
| Category | Benchmark | Phi-3-Mini-128K-Ins | Gemma-7B | Mistral-7B | Mixtral-8x7B | Llama-3-8B-Ins | GPT3.5-Turbo-1106 |
|
||||
| :----------| :-----------| :---------------------| :----------| :------------| :--------------| :----------------| :-------------------|
|
||||
| Popular aggregated benchmark | AGI Eval <br>5-shot| 39.5 | 42.1 | 35.1 | 45.2 | 42 | 48.4 |
|
||||
| | MMLU <br>5-shot | 69.7 | 63.6 | 61.7 | 70.5 | 66.5 | 71.4 |
|
||||
| | BigBench Hard <br>3-shot | 72.1 | 59.6 | 57.3 | 69.7 | 51.5 | 68.3 |
|
||||
| Language Understanding | ANLI <br>7-shot | 52.3 | 48.7 | 47.1 | 55.2 | 57.3 | 58.1 |
|
||||
| | HellaSwag <br>5-shot | 70.5 | 49.8 | 58.5 | 70.4 | 71.1 | 78.8 |
|
||||
| Reasoning | ARC Challenge <br>10-shot | 85.5 | 78.3 | 78.6 | 87.3 | 82.8 | 87.4 |
|
||||
| | BoolQ <br>0-shot | 77.1 | 66 | 72.2 | 76.6 | 80.9 | 79.1 |
|
||||
| | MedQA <br>2-shot | 56.4 | 49.6 | 50 | 62.2 | 60.5 | 63.4 |
|
||||
| | OpenBookQA <br>10-shot | 78.8 | 78.6 | 79.8 | 85.8 | 82.6 | 86 |
|
||||
| | PIQA <br>5-shot | 80.1 | 78.1 | 77.7 | 86 | 75.7 | 86.6 |
|
||||
| | GPQA <br>0-shot | 29.7 | 2.9 | 15 | 6.9 | 32.4 | 29.9 |
|
||||
| | Social IQA <br>5-shot | 74.7 | 65.5 | 74.6 | 75.9 | 73.9 | 68.3 |
|
||||
| | TruthfulQA (MC2) <br>10-shot | 64.8 | 52.1 | 53 | 60.1 | 63.2 | 67.7 |
|
||||
| | WinoGrande <br>5-shot | 71.0 | 55.6 | 54.2 | 62 | 65 | 68.8 |
|
||||
| Factual Knowledge | TriviaQA <br>5-shot | 57.8 | 72.3 | 75.2 | 82.2 | 67.7 | 85.8 |
|
||||
| Math | GSM8K CoTT <br>8-shot | 85.3 | 59.8 | 46.4 | 64.7 | 77.4 | 78.1 |
|
||||
| Code Generation | HumanEval <br>0-shot | 60.4 | 34.1 | 28.0 | 37.8 | 60.4 | 62.2 |
|
||||
| | MBPP <br>3-shot | 70.0 | 51.5 | 50.8 | 60.2 | 67.7 | 77.8 |
|
||||
| **Average** | | **66.4** | **56.0** | **56.4** | **64.4** | **65.5** | **70.3** |
|
||||
|
||||
**Long Context**: Phi-3 Mini-128K-Instruct supports 128K context length, therefore the model is capable of several long context tasks including long document/meeting summarization, long document QA.
|
||||
|
||||
| Benchmark | Phi-3 Mini-128K-Instruct | Mistral-7B | Mixtral 8x7B | LLaMA-3-8B-Instruct |
|
||||
| :---------------| :--------------------------|:------------|:--------------|:---------------------|
|
||||
| GovReport | 25.3 | 4.9 | 20.3 | 10.3 |
|
||||
| QMSum | 21.9 | 15.5 | 20.6 | 2.9 |
|
||||
| Qasper | 41.6 | 23.5 | 26.6 | 8.1 |
|
||||
| SQuALITY | 24.1 | 14.7 | 16.2 | 25 |
|
||||
| SummScreenFD | 16.8 | 9.3 | 11.3 | 5.1 |
|
||||
| **Average** | **25.9** | **13.6** | **19.0** | **10.3** |
|
||||
|
||||
We take a closer look at different categories across 100 public benchmark datasets at the table below:
|
||||
|
||||
| Category | Phi-3-Mini-128K-Instruct | Gemma-7B | Mistral-7B | Mixtral 8x7B | Llama-3-8B-Instruct | GPT-3.5-Turbo |
|
||||
|:----------|:--------------------------|:----------|:------------|:--------------|:---------------------|:---------------|
|
||||
| Popular aggregated benchmark | 60.6 | 59.4 | 56.5 | 66.2 | 59.9 | 67.0 |
|
||||
| Reasoning | 69.4 | 60.3 | 62.8 | 68.1 | 69.6 | 71.7 |
|
||||
| Language understanding | 57.5 | 57.6 | 52.5 | 66.1 | 63.2 | 67.7 |
|
||||
| Code generation | 61.0 | 45.6 | 42.9 | 52.7 | 56.4 | 70.4 |
|
||||
| Math | 51.6 | 35.8 | 25.4 | 40.3 | 41.1 | 52.8 |
|
||||
| Factual knowledge | 35.8 | 46.7 | 49.8 | 58.6 | 43.1 | 63.4 |
|
||||
| Multilingual | 56.4 | 66.5 | 57.4 | 66.7 | 66.6 | 71.0 |
|
||||
| Robustness | 61.1 | 38.4 | 40.6 | 51.0 | 64.5 | 69.3 |
|
||||
|
||||
Overall, the model with only 3.8B-param achieves a similar level of language understanding and reasoning ability as much larger models. However, it is still fundamentally limited by its size for certain tasks. The model simply does not have the capacity to store too much world knowledge, which can be seen for example with low performance on TriviaQA. However, we believe such weakness can be resolved by augmenting Phi-3-Mini with a search engine.
|
||||
|
||||
## Cross Platform Support
|
||||
|
||||
[ONNX runtime](https://onnxruntime.ai/blogs/accelerating-phi-3) now supports Phi-3 mini models across platforms and hardware.
|
||||
|
||||
Optimized phi-3 models are also published here in ONNX format, to run with ONNX Runtime on CPU and GPU across devices, including server platforms, Windows, Linux and Mac desktops, and mobile CPUs, with the precision best suited to each of these targets. DirectML GPU acceleration is supported for Windows desktops GPUs (AMD, Intel, and NVIDIA).
|
||||
|
||||
Along with DML, ONNX Runtime provides cross platform support for Phi3 mini across a range of devices CPU, GPU, and mobile.
|
||||
|
||||
Here are some of the optimized configurations we have added:
|
||||
|
||||
1. ONNX models for int4 DML: Quantized to int4 via AWQ
|
||||
2. ONNX model for fp16 CUDA
|
||||
3. ONNX model for int4 CUDA: Quantized to int4 via RTN
|
||||
4. ONNX model for int4 CPU and Mobile: Quantized to int4 via RTN
|
||||
|
||||
## Software
|
||||
|
||||
* [PyTorch](https://github.com/pytorch/pytorch)
|
||||
* [Transformers](https://github.com/huggingface/transformers)
|
||||
* [Flash-Attention](https://github.com/HazyResearch/flash-attention)
|
||||
|
||||
## Hardware
|
||||
Note that by default, the Phi-3 Mini-128K-Instruct model uses flash attention, which requires certain types of GPU hardware to run. We have tested on the following GPU types:
|
||||
* NVIDIA A100
|
||||
* NVIDIA A6000
|
||||
* NVIDIA H100
|
||||
|
||||
If you want to run the model on:
|
||||
* NVIDIA V100 or earlier generation GPUs: call AutoModelForCausalLM.from_pretrained() with attn_implementation="eager"
|
||||
* Optimized inference on GPU, CPU, and Mobile: use the **ONNX** models [128K](https://aka.ms/phi3-mini-128k-instruct-onnx)
|
||||
|
||||
## License
|
||||
|
||||
The model is licensed under the [MIT license](https://huggingface.co/microsoft/Phi-3-mini-128k/resolve/main/LICENSE).
|
||||
|
||||
## Trademarks
|
||||
|
||||
This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow [Microsoft’s Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks). Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party’s policies.
|
||||
29
models/Phi-3-mini-128k-instruct/model.yaml
Normal file
29
models/Phi-3-mini-128k-instruct/model.yaml
Normal file
@@ -0,0 +1,29 @@
|
||||
model:
|
||||
name: Phi-3-mini-128k-instruct
|
||||
display_name: microsoft/Phi-3-mini-128k-instruct
|
||||
description: No description available.
|
||||
publisher_original: mit
|
||||
publisher_quantized: Community
|
||||
license: mit
|
||||
license_url: https://huggingface.co/microsoft/Phi-3-mini-128k-instruct/blob/main/LICENSE
|
||||
publish_date: '2025-03-02'
|
||||
modality: text
|
||||
thinking_model: true
|
||||
tokenizer:
|
||||
files:
|
||||
- tokenizer.json
|
||||
- tokenizer.model
|
||||
- tokenizer_config.json
|
||||
architecture: transformer
|
||||
formats:
|
||||
- type: safetensors
|
||||
variants:
|
||||
- id: model
|
||||
label: model
|
||||
bits: 16
|
||||
context_length: 4096
|
||||
size_bytes: 7642181880
|
||||
hf_repo: https://huggingface.co/microsoft/Phi-3-mini-128k-instruct
|
||||
files:
|
||||
- model-00001-of-00002.safetensors
|
||||
- model-00002-of-00002.safetensors
|
||||
3
registry.json
Normal file
3
registry.json
Normal file
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:c0fc08cc9220bbed0f9c5702021f91a265ade001894e648fbaa5d19bbedc5fd3
|
||||
size 596
|
||||
5
tools/README.md
Normal file
5
tools/README.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Setup
|
||||
|
||||
```
|
||||
pip install pyyaml huggingface_hub
|
||||
```
|
||||
49
tools/cleanup.sh
Executable file
49
tools/cleanup.sh
Executable file
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# cleanup.sh - Commits, pushes, and prunes LFS files.
|
||||
#
|
||||
# - Detects *untracked* files (git status --porcelain), so we don’t skip commits.
|
||||
# - Uses 'git add --renormalize .' so new/changed .gitattributes rules convert
|
||||
# existing files into LFS pointers on re-add.
|
||||
# - Keeps the prune step to free local disk space after a successful push.
|
||||
#
|
||||
# Usage: ./tools/cleanup.sh <commit-message>
|
||||
|
||||
if [ "$#" -ne 1 ]; then
|
||||
echo "Usage: $0 <commit-message>" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
COMMIT_MESSAGE="$1"
|
||||
|
||||
# Detect any changes, including untracked.
|
||||
if [[ -z "$(git status --porcelain=v1)" ]]; then
|
||||
echo "No new files or changes to commit. Skipping commit and push."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Committing and pushing changes..."
|
||||
|
||||
# Make sure .gitattributes changes are included and normalization runs,
|
||||
# so LFS filters rewrite eligible files as pointers.
|
||||
git add .gitattributes || true
|
||||
git add --renormalize .
|
||||
|
||||
# If nothing ended up staged (e.g. only ignored files changed), exit gracefully.
|
||||
if git diff --cached --quiet; then
|
||||
echo "No staged changes after normalization. Skipping commit and push."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git commit -m "$COMMIT_MESSAGE"
|
||||
git push
|
||||
|
||||
# Optional but useful: ensure all LFS objects are on the remote.
|
||||
# Uncomment if you want belt-and-suspenders uploads.
|
||||
# git lfs push origin --all
|
||||
|
||||
echo "Pruning local LFS files..."
|
||||
git lfs prune --force
|
||||
|
||||
echo "✅ Cleanup complete."
|
||||
167
tools/download.py
Normal file
167
tools/download.py
Normal file
@@ -0,0 +1,167 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
download.py - Download/repair model files and update model.yaml metadata.
|
||||
|
||||
Usage:
|
||||
./tools/download.py models/llama-2-7b-chat/model.yaml
|
||||
|
||||
- Always (re)runs snapshot_download with resume support, so partially
|
||||
fetched directories get completed instead of being skipped.
|
||||
- Updates YAML after each variant with fresh file list + total size.
|
||||
- Tracks LFS via sensible patterns (plus a size threshold fallback).
|
||||
- Emits clear logs so you can see progress per variant.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import yaml
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
from huggingface_hub import snapshot_download
|
||||
|
||||
LFS_PATTERNS: list[str] = [
|
||||
# Extensions commonly used for model artifacts
|
||||
"*.safetensors",
|
||||
"*.bin",
|
||||
"*.pt",
|
||||
"*.gguf",
|
||||
"*.onnx",
|
||||
"*.ckpt",
|
||||
"*.tensors",
|
||||
"*.npz",
|
||||
"*.tar",
|
||||
"*.tar.gz",
|
||||
"*.zip",
|
||||
]
|
||||
|
||||
SIZE_THRESHOLD_BYTES = 1_000_000 # 1 MB fallback if a file doesn't match any pattern
|
||||
|
||||
def run(cmd: list[str], check: bool = True) -> None:
|
||||
subprocess.run(cmd, check=check)
|
||||
|
||||
|
||||
def track_lfs_patterns(patterns: Iterable[str]) -> None:
|
||||
"""
|
||||
Track a set of patterns in Git LFS. This is idempotent; it just
|
||||
appends to .gitattributes as needed.
|
||||
"""
|
||||
for patt in patterns:
|
||||
try:
|
||||
run(["git", "lfs", "track", patt], check=False)
|
||||
except Exception:
|
||||
# Non-fatal: we’ll still fall back to per-file size rule below.
|
||||
pass
|
||||
|
||||
|
||||
def list_files_under(root: Path) -> list[Path]:
|
||||
return [p for p in root.rglob("*") if p.is_file()]
|
||||
|
||||
|
||||
def ensure_repo_root() -> None:
|
||||
# best effort: warn (but don’t die) if not in a git repo
|
||||
try:
|
||||
subprocess.run(["git", "rev-parse", "--is-inside-work-tree"], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
except Exception:
|
||||
print("⚠️ Not inside a Git repository? Git/LFS steps may fail.", file=sys.stderr)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if len(sys.argv) != 2:
|
||||
print(f"Usage: {sys.argv[0]} <path-to-model.yaml>", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
model_yaml_path = Path(sys.argv[1])
|
||||
if not model_yaml_path.exists():
|
||||
print(f"Model YAML not found: {model_yaml_path}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
ensure_repo_root()
|
||||
|
||||
# Load YAML
|
||||
with open(model_yaml_path, "r", encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f) or {}
|
||||
|
||||
model_dir = model_yaml_path.parent
|
||||
|
||||
# Proactively set up LFS tracking by patterns (idempotent)
|
||||
track_lfs_patterns(LFS_PATTERNS)
|
||||
|
||||
# Iterate formats & variants
|
||||
formats = (data.get("model") or {}).get("formats") or []
|
||||
for fmt in formats:
|
||||
variants = fmt.get("variants") or []
|
||||
for variant in variants:
|
||||
variant_id = variant.get("id")
|
||||
hf_repo = variant.get("hf_repo")
|
||||
|
||||
if not hf_repo or not variant_id:
|
||||
continue
|
||||
|
||||
dest_path = model_dir / variant_id
|
||||
dest_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
repo_id = hf_repo.replace("https://huggingface.co/", "")
|
||||
print(f"\n[DL] Downloading/resuming variant '{variant_id}' from '{repo_id}' into '{dest_path}'")
|
||||
|
||||
# Always call snapshot_download with resume enabled. This will:
|
||||
# - no-op for already-complete files
|
||||
# - resume partials
|
||||
# - fetch any missing files
|
||||
try:
|
||||
snapshot_download(
|
||||
repo_id=repo_id,
|
||||
local_dir=str(dest_path),
|
||||
local_dir_use_symlinks=False,
|
||||
resume_download=True, # explicit
|
||||
# You can add allow_patterns / ignore_patterns if you want to filter
|
||||
# allow_patterns=None,
|
||||
# ignore_patterns=None,
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"❌ snapshot_download failed for {variant_id}: {e}", file=sys.stderr)
|
||||
raise
|
||||
|
||||
# Scan files, compute size, and ensure big files are tracked by LFS
|
||||
files_list: list[str] = []
|
||||
total_size_bytes = 0
|
||||
|
||||
for p in list_files_under(dest_path):
|
||||
rel = p.relative_to(model_dir)
|
||||
files_list.append(str(rel))
|
||||
try:
|
||||
size = p.stat().st_size
|
||||
except FileNotFoundError:
|
||||
# if a file was removed mid-scan, skip it
|
||||
continue
|
||||
total_size_bytes += size
|
||||
|
||||
# Fallback: ensure big files get tracked even if patterns miss them
|
||||
if size > SIZE_THRESHOLD_BYTES:
|
||||
# Idempotent; harmless if already tracked.
|
||||
run(["git", "lfs", "track", str(p)], check=False)
|
||||
|
||||
files_list.sort()
|
||||
variant["files"] = files_list
|
||||
variant["size_bytes"] = int(total_size_bytes)
|
||||
|
||||
# Save updated YAML progressively after each variant
|
||||
with open(model_yaml_path, "w", encoding="utf-8") as f:
|
||||
yaml.dump(data, f, sort_keys=False, allow_unicode=True)
|
||||
|
||||
print(f"✅ Updated {model_yaml_path} for variant '{variant_id}'")
|
||||
# Run cleanup script to commit, push, and prune
|
||||
commit_message = f"Add/update model files for {model_dir.name}/{variant_id}"
|
||||
print(f"🧹 Running cleanup for {variant_id}...")
|
||||
try:
|
||||
run(["./tools/cleanup.sh", commit_message], check=True)
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"❌ cleanup.sh failed (continue to next variant): {e}", file=sys.stderr)
|
||||
# Decide whether to continue or abort; continuing is usually fine.
|
||||
# raise # uncomment to abort on failure
|
||||
|
||||
print(f"\n✅ Download and YAML update complete for {model_yaml_path}.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
87
tools/download.sh
Executable file
87
tools/download.sh
Executable file
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# download.sh - Download model files and update model.yaml metadata.
|
||||
#
|
||||
# This script reads a model.yaml file, downloads the complete model data from
|
||||
# the specified Hugging Face repository, and then updates the 'files' array
|
||||
# in the YAML with the paths of the downloaded files.
|
||||
#
|
||||
# This approach is more robust than specifying files manually, as it ensures
|
||||
# the YAML reflects the actual downloaded content.
|
||||
#
|
||||
# Usage: ./tools/download.sh models/llama-2-7b/model.yaml
|
||||
|
||||
if [ "$#" -ne 1 ]; then
|
||||
echo "Usage: $0 <path-to-model.yaml>" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
MODEL_YAML="$1"
|
||||
MODEL_DIR=$(dirname "$MODEL_YAML")
|
||||
|
||||
if [ ! -f "$MODEL_YAML" ]; then
|
||||
echo "Model YAML not found: $MODEL_YAML" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Ensure yq is installed
|
||||
if ! command -v yq &> /dev/null; then
|
||||
echo "Error: yq is not installed. Install it with: pip install yq or brew install yq" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Ensure huggingface-cli is installed
|
||||
if ! command -v huggingface-cli &> /dev/null; then
|
||||
echo "Error: huggingface-cli is not installed. Install it with: pip install huggingface_hub" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Reading metadata from $MODEL_YAML..."
|
||||
|
||||
# Create a temporary file to store the updated YAML content
|
||||
TMP_YAML=$(mktemp)
|
||||
trap 'rm -f "$TMP_YAML"' EXIT
|
||||
|
||||
cp "$MODEL_YAML" "$TMP_YAML"
|
||||
|
||||
# Loop over each format and variant to download files
|
||||
yq -r '.formats[] | . as $format | .variants[] | . as $variant | "\($format.type)\|\($variant.id)\|\($variant.hf_repo)"' "$MODEL_YAML" | while IFS='|' read -r format_type variant_id hf_repo; do
|
||||
echo
|
||||
echo "Processing variant: $variant_id (format: $format_type) from $hf_repo"
|
||||
|
||||
DEST_PATH="$MODEL_DIR/$variant_id"
|
||||
mkdir -p "$DEST_PATH"
|
||||
|
||||
# Check if files are already downloaded by checking for a non-empty directory
|
||||
if [ -n "$(ls -A "$DEST_PATH" 2>/dev/null)" ]; then
|
||||
echo "[OK] Files for $variant_id already exist in $DEST_PATH. Skipping download."
|
||||
else
|
||||
repo_id=${hf_repo#https://huggingface.co/}
|
||||
echo "[DL] Downloading files for $variant_id from $repo_id..."
|
||||
huggingface-cli download "$repo_id" --local-dir "$DEST_PATH" --local-dir-use-symlinks False
|
||||
fi
|
||||
|
||||
# After downloading, list the downloaded files relative to the model directory
|
||||
downloaded_files=()
|
||||
while IFS= read -r file; do
|
||||
downloaded_files+=("$(realpath --relative-to="$MODEL_DIR" "$file")")
|
||||
done < <(find "$DEST_PATH" -type f)
|
||||
|
||||
# Update the YAML file with the list of downloaded files for the current variant
|
||||
echo "Updating $MODEL_YAML with downloaded file paths for $variant_id..."
|
||||
# Create a yq expression to update the files for the specific variant
|
||||
yq_exp="(.formats[] | select(.type == \"$format_type\") | .variants[] | select(.id == \"$variant_id\") | .files) = []"
|
||||
yq eval -i "$yq_exp" "$TMP_YAML"
|
||||
|
||||
for file in "${downloaded_files[@]}"; do
|
||||
yq_exp="(.formats[] | select(.type == \"$format_type\") | .variants[] | select(.id == \"$variant_id\") | .files) += [\"$file\"]"
|
||||
yq eval -i "$yq_exp" "$TMP_YAML"
|
||||
done
|
||||
done
|
||||
|
||||
# Replace the original YAML with the updated one
|
||||
mv "$TMP_YAML" "$MODEL_YAML"
|
||||
|
||||
echo
|
||||
echo "✅ Download and YAML update complete for $MODEL_YAML."
|
||||
34
tools/generate-registry.py
Normal file
34
tools/generate-registry.py
Normal file
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import sys
|
||||
import yaml
|
||||
import json
|
||||
|
||||
def collect_models(models_root):
|
||||
registry = []
|
||||
for root, dirs, files in os.walk(models_root):
|
||||
if "model.yaml" in files:
|
||||
model_path = os.path.join(root, "model.yaml")
|
||||
try:
|
||||
with open(model_path, 'r', encoding='utf-8') as f:
|
||||
model_data = yaml.safe_load(f)
|
||||
registry.append(model_data)
|
||||
except Exception as e:
|
||||
print(f"❌ Failed to parse {model_path}: {e}", file=sys.stderr)
|
||||
return registry
|
||||
|
||||
if __name__ == "__main__":
|
||||
repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
||||
models_root = os.path.join(repo_root, "models")
|
||||
output_path = os.path.join(repo_root, "registry.json")
|
||||
|
||||
if not os.path.isdir(models_root):
|
||||
print(f"❌ Models directory not found: {models_root}")
|
||||
sys.exit(1)
|
||||
|
||||
registry = collect_models(models_root)
|
||||
|
||||
with open(output_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(registry, f, indent=2, ensure_ascii=False)
|
||||
|
||||
print(f"✅ Registry written to {output_path} with {len(registry)} models.")
|
||||
134
tools/generate_model_yaml.py
Normal file
134
tools/generate_model_yaml.py
Normal file
@@ -0,0 +1,134 @@
|
||||
from huggingface_hub import HfApi, HfFileSystem
|
||||
from pathlib import Path
|
||||
import yaml
|
||||
import requests
|
||||
import os
|
||||
from datetime import datetime
|
||||
from collections import defaultdict
|
||||
import re
|
||||
import sys
|
||||
|
||||
|
||||
def generate_model_bundle(repo_id: str, output_dir: str):
|
||||
api = HfApi()
|
||||
fs = HfFileSystem()
|
||||
model_info = api.model_info(repo_id)
|
||||
|
||||
# Create output path
|
||||
out_path = Path(output_dir)
|
||||
out_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# ----- 1. Fetch metadata -----
|
||||
model_card = model_info.cardData or {}
|
||||
tags = model_info.tags or []
|
||||
files = api.list_repo_files(repo_id)
|
||||
|
||||
# ----- 2. Filter files -----
|
||||
model_files = [f for f in files if f.endswith(".gguf") or f.endswith(".safetensors")]
|
||||
tokenizer_files = [f for f in files if "tokenizer" in f.lower()]
|
||||
license_file = next((f for f in files if "license" in f.lower()), None)
|
||||
|
||||
# ----- 3. Fetch README -----
|
||||
readme_url = f"https://huggingface.co/{repo_id}/raw/main/README.md"
|
||||
readme_path = out_path / "README.md"
|
||||
try:
|
||||
r = requests.get(readme_url)
|
||||
r.raise_for_status()
|
||||
readme_path.write_text(r.text)
|
||||
except Exception:
|
||||
readme_path.write_text(f"# README for {repo_id}\n(Not found on HuggingFace)")
|
||||
|
||||
# ----- 4. Fetch LICENSE -----
|
||||
if license_file:
|
||||
license_text = api.hf_hub_download(repo_id, license_file)
|
||||
license_dst = out_path / Path(license_file).name
|
||||
Path(license_dst).write_text(Path(license_text).read_text())
|
||||
|
||||
# ----- 5. Build variant groups -----
|
||||
variants = []
|
||||
shard_groups = defaultdict(list)
|
||||
unsharded_files = []
|
||||
|
||||
for f in model_files:
|
||||
match = re.match(r"(.+)-\d+-of-\d+\.safetensors$", f)
|
||||
if match:
|
||||
prefix = match.group(1)
|
||||
shard_groups[prefix].append(f)
|
||||
else:
|
||||
unsharded_files.append(f)
|
||||
|
||||
for prefix, files_group in shard_groups.items():
|
||||
total_size = sum(fs.info(f"hf://{repo_id}/{f}").get("size", 0) for f in files_group)
|
||||
context_length = 128000 if "128k" in prefix.lower() else 4096
|
||||
bits = 16 # Assume safetensors shards are FP16
|
||||
|
||||
variants.append({
|
||||
"id": prefix,
|
||||
"label": prefix,
|
||||
"bits": bits,
|
||||
"context_length": context_length,
|
||||
"size_bytes": total_size,
|
||||
"hf_repo": f"https://huggingface.co/{repo_id}",
|
||||
"files": sorted(files_group)
|
||||
})
|
||||
|
||||
for f in unsharded_files:
|
||||
ext = Path(f).suffix
|
||||
size_bytes = fs.info(f"hf://{repo_id}/{f}").get("size", 0)
|
||||
bits = 16 if "fp16" in f.lower() or ext == ".safetensors" else 4 if "q4" in f.lower() else 8
|
||||
context_length = 128000 if "128k" in f.lower() else 4096
|
||||
|
||||
variants.append({
|
||||
"id": Path(f).stem,
|
||||
"label": f,
|
||||
"bits": bits,
|
||||
"context_length": context_length,
|
||||
"size_bytes": size_bytes,
|
||||
"hf_repo": f"https://huggingface.co/{repo_id}",
|
||||
"files": [f]
|
||||
})
|
||||
|
||||
# ----- 6. Handle date -----
|
||||
last_modified = model_info.lastModified
|
||||
if isinstance(last_modified, str):
|
||||
last_modified = datetime.fromisoformat(last_modified.replace("Z", "+00:00"))
|
||||
|
||||
# ----- 7. YAML data -----
|
||||
yaml_data = {
|
||||
"model": {
|
||||
"name": repo_id.split("/")[-1],
|
||||
"display_name": model_card.get("title", repo_id),
|
||||
"description": model_card.get("summary", "No description available."),
|
||||
"publisher_original": model_card.get("license", "other"),
|
||||
"publisher_quantized": "Community",
|
||||
"license": model_card.get("license", "other"),
|
||||
"license_url": f"https://huggingface.co/{repo_id}/blob/main/{license_file}" if license_file else "N/A",
|
||||
"publish_date": last_modified.date().isoformat(),
|
||||
"modality": "text",
|
||||
"thinking_model": True,
|
||||
"tokenizer": {"files": tokenizer_files},
|
||||
"architecture": model_card.get("model_architecture", "transformer"),
|
||||
"formats": [{
|
||||
"type": "gguf" if any(f.endswith(".gguf") for f in model_files) else "safetensors",
|
||||
"variants": variants
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
with open(out_path / "model.yaml", "w") as f:
|
||||
yaml.dump(yaml_data, f, sort_keys=False)
|
||||
|
||||
return str(out_path)
|
||||
|
||||
|
||||
# -------- Entry point for CLI --------
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 3:
|
||||
print("Usage: python generate_model_yaml.py <huggingface/repo-id> <output-folder>")
|
||||
sys.exit(1)
|
||||
|
||||
repo_id = sys.argv[1]
|
||||
output_dir = sys.argv[2]
|
||||
|
||||
output_path = generate_model_bundle(repo_id, output_dir)
|
||||
print(f"✅ Model bundle generated at: {output_path}")
|
||||
60
tools/verify-checksums.py
Normal file
60
tools/verify-checksums.py
Normal file
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
import os
|
||||
import yaml
|
||||
import hashlib
|
||||
|
||||
def sha256sum(filename, buf_size=65536):
|
||||
sha256 = hashlib.sha256()
|
||||
with open(filename, 'rb') as f:
|
||||
while True:
|
||||
data = f.read(buf_size)
|
||||
if not data:
|
||||
break
|
||||
sha256.update(data)
|
||||
return sha256.hexdigest()
|
||||
|
||||
def verify_model(model_yaml_path):
|
||||
if not os.path.isfile(model_yaml_path):
|
||||
print(f"❌ Model YAML not found: {model_yaml_path}")
|
||||
sys.exit(1)
|
||||
|
||||
with open(model_yaml_path, 'r', encoding='utf-8') as f:
|
||||
model_data = yaml.safe_load(f)
|
||||
|
||||
base_dir = os.path.dirname(model_yaml_path)
|
||||
all_ok = True
|
||||
|
||||
for fmt in model_data.get("formats", []):
|
||||
for variant in fmt.get("variants", []):
|
||||
for file_path in variant.get("files", []):
|
||||
checksum_expected = variant.get("checksums", {}).get(file_path)
|
||||
abs_path = os.path.join(base_dir, file_path)
|
||||
|
||||
if not os.path.isfile(abs_path):
|
||||
print(f"❌ Missing file: {abs_path}")
|
||||
all_ok = False
|
||||
continue
|
||||
|
||||
if not checksum_expected:
|
||||
print(f"⚠️ No checksum for {file_path}, skipping verification.")
|
||||
continue
|
||||
|
||||
checksum_actual = sha256sum(abs_path)
|
||||
if checksum_actual.lower() == checksum_expected.lower():
|
||||
print(f"✅ {file_path} OK")
|
||||
else:
|
||||
print(f"❌ {file_path} checksum mismatch! Expected {checksum_expected}, got {checksum_actual}")
|
||||
all_ok = False
|
||||
|
||||
if all_ok:
|
||||
print("✅ All files verified successfully.")
|
||||
else:
|
||||
print("❌ Verification failed.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 2:
|
||||
print(f"Usage: {sys.argv[0]} <path-to-model.yaml>")
|
||||
sys.exit(1)
|
||||
|
||||
verify_model(sys.argv[1])
|
||||
38
tools/watcher.sh
Executable file
38
tools/watcher.sh
Executable file
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# watcher.sh - Watches for new models, downloads their files, and tracks large files with Git LFS.
|
||||
#
|
||||
# This script continuously scans the 'models' directory for 'model.yaml' files.
|
||||
# For each model, it runs the 'download.sh' script to fetch model files from
|
||||
# Hugging Face. After downloading, it identifies files larger than 1MB and
|
||||
# ensures they are tracked by Git LFS.
|
||||
#
|
||||
# Usage: ./tools/watcher.sh
|
||||
# Run from the root of the repository.
|
||||
|
||||
# This script should be run from the root of the repository.
|
||||
if [ ! -d ".git" ]; then
|
||||
echo "Error: This script must be run from the root of the repository." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
while true; do
|
||||
echo "🔍 Starting model discovery cycle..."
|
||||
|
||||
# Find all model.yaml files in the models directory
|
||||
find models -name model.yaml | while read -r MODEL_YAML; do
|
||||
MODEL_DIR=$(dirname "$MODEL_YAML")
|
||||
|
||||
echo "--------------------------------------------------"
|
||||
echo "Processing model in $MODEL_DIR"
|
||||
|
||||
# The download script will now handle LFS tracking and cleanup for each variant.
|
||||
python3 ./tools/download.py "$MODEL_YAML"
|
||||
done
|
||||
|
||||
echo "--------------------------------------------------"
|
||||
echo "✅ Watcher finished a cycle. Sleeping for 60 seconds before next scan."
|
||||
echo "Press [CTRL+C] to stop."
|
||||
sleep 60
|
||||
done
|
||||
Reference in New Issue
Block a user