microsoft / phi-3-mini-4k-instruct

Model Summary

DevelopersMicrosoft GenAI
DescriptionPhi-3 Mini is a lightweight, state-of-the-art open model built upon datasets used for Phi-2 - synthetic data and filtered publicly available websites - with a focus on very high-quality, reasoning dense data. The model belongs to the Phi-3 model family, and the medium version comes in two variants 4K and 128K which is the context length (in tokens) it can support. The model underwent a rigorous enhancement process, incorporating both supervised fine-tuning and direct preference optimization to ensure precise instruction adherence and robust safety measures. This model is ready for commercial and research use.
ArchitectureDense decoder-only Transformer model using the same tokenizer as Phi-3 Mini. Phi-3 Mini has 3.8B parameters.
Release datesJune 27, 2024
Third-Party Community ConsiderationThis model is not owned or developed by NVIDIA. This model has been developed and built to a third-party’s requirements for this application and use case; see link to the (Phi-3 Repo) Model Card.
LicenseMIT
InputsText. It’s best suited for prompts using the chat format.
Context length4K tokens
OutputsText (generated in response to the input)
GPUS512 H100-80G
Training time10 days
Training data4.9T tokens
DatesOur models were trained between May and June 2024.
StatusThis is a static model trained on an offline dataset with cutoff date October 2023 for publicly available data. Future versions of the tuned models may be released as we improve models.

Intended Use

Primary use casesThe model is intended for broad commercial and research use in English. The model provides uses for general purpose AI systems and applications which require 1) memory/compute constrained environments;
  1. latency bound scenarios; 3) strong reasoning (especially 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.
Out-of-scope use cases

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 fairness 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.

Usage

Input formats

Given the nature of the training data, the Phi-3 Mini-4K-Instruct model
is best suited for prompts using the chat format as follows:

<|system|>
You are a helpful assistant.<|end|>

<|user|>
How to explain Internet for a medieval knight?<|end|>
<|assistant|>

Loading the model locally

After obtaining the Phi-3 Mini-4K-Instruct model checkpoints, users can
use this sample code for inference.

import torch

from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline

torch.random.manual_seed(0)

model = AutoModelForCausalLM.from_pretrained(

"microsoft/Phi-3-mini-4k-instruct",

device_map="cuda",

torch_dtype="auto",

trust_remote_code=True,

)

tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-4k-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'])

Cross Platform Support

ONNX runtime 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 R

Data Overview

Training 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.

Benchmark datasets

We evaluated the model across a breadth of public and internal
benchmarks to understand the model capabilities in the most
comprehensive way under multiple tasks and conditions. More
specifically,

  • Reasoning:

    • Winogrande: commonsense reasoning around pronoun resolution

    • PIQA: physical commonsense reasoning around everyday situations

    • ARC-challenge: grade-school multiple choice science questions

    • GPQA: very hard questions written and validated by experts in
      biology, physics, and chemistry

    • MedQA: medical questions answering

    • Social IQA: social commonsense intelligence

    • BoolQ: natural questions from context

    • TruthfulQA: grounded reasoning

  • Language understanding:

    • HellaSwag: commonsense natural language inference around everyday
      events

    • ANLI: adversarial natural language inference

    • LAMBADA: word prediction given a passage.

  • World knowledge:

    • TriviaQA: trivia question on general topics
  • Math:

    • GSM8K: grade-school math word problems

    • GSM8K Hard: grade-school math word problems with large values and
      some absurdity.

    • MATH: challenging competition math problems

  • Code:

    • HumanEval, MBPP: python coding tasks

    • Spider: SQL query tasks

  • Multilingual:

    • MGSM: multilingual grade-school math

    • MEGA: multilingual NLP tasks

  • Popular aggregated datasets: MMLU, BigBench-Hard, AGI Eval

  • Multi-turn conversations:

    • Data generated by In-house adversarial conversation simulation tool
  • Single-turn trustworthiness evaluation:

    • DecodingTrust: a collection of trustworthiness benchmark in eight
      different perspectives

    • XSTest: exaggerated safety evaluation

    • Toxigen: adversarial and hate speech detection

  • Red Team:

    • Responses to prompts provided by AI Red Team at Microsoft

Safety

Approach

Phi-3 family of models has adopted a robust safety post-training
approach. This approach leverages a variety of both open-source and
in-house generated datasets. The overall technique employed to do the
safety alignment is a combination of SFT (Supervised Fine-Tuning) and a
modified version of RLHF (Reinforcement Learning from Human Feedback) by
utilizing human-labeled and synthetic datasets, including publicly
available datasets focusing on helpfulness and harmlessness as well as
various questions and answers targeted to multiple safety categories.

Safety Evaluation and Red-Teaming

Prior to release, Phi-3 family of models followed a multi-faceted
evaluation approach. Quantitative evaluation was conducted with multiple
open-source safety benchmarks and in-house tools utilizing adversarial
conversation simulation. For qualitative safety evaluation, we
collaborated with the AI Red Team at Microsoft to assess safety risks
posed by Phi-3-Medium in both average and adversarial user scenarios.
The assessment was done in predetermined eight risk categories with
automated scoring followed by thorough manual reviews of the model
responses.

Please refer to the technical report for more details of our safety alignment.

Model Quality

To understand the capabilities, we compare Phi-3 Mini with a set of
models over a variety of benchmarks using our internal benchmark
platform (See Appendix A for benchmark methodology). At the
high-level overview of the model quality on representative benchmarks:

CategoryBenchmarkPhi-3-Mini-4K-InsGemma-7BMistral-7bMixtral-8x7bLlama-3-8B-InsGPT3.5-Turbo-1106
Popular aggregated benchmarkAGI Eval39.042.135.145.24248.4
MMLU70.963.661.770.566.571.4
BigBench Hard73.559.657.369.751.568.3
Language UnderstandingANLI53.648.747.155.257.358.1
HellaSwag75.349.858.570.471.178.8
ReasoningARC Challenge86.378.378.687.382.887.4
BoolQ78.16672.276.680.979.1
MedQA56.549.65062.260.563.4
OpenBookQA82.278.679.885.882.686
PIQA83.578.177.78675.786.6
GPQA30.62.9156.932.430.8
Social IQA77.665.574.675.973.968.3
TruthfulQA (MC2)64.752.15360.163.267.7
WinoGrande71.655.654.2626568.8
Factual KnowledgeTriviaQA61.472.375.282.267.785.8
MathGSM8K CoT85.759.846.464.777.478.1
Code GenerationHumanEval57.334.128.037.860.462.2
MBPP69.851.550.860.267.777.8
Average67.656.056.464.465.570.4

We take a closer look at different categories across 80 public benchmark
datasets at the table below:

CategoryPhi-3-Mini-4K-InstructGemma-7BMistral-7BMixtral 8x7BLlama-3-8B-InstructGPT-3.5-Turbo
Popular aggregated benchmark61.159.456.566.259.967.0
Reasoning70.860.362.868.169.671.8
Language understanding60.557.652.566.163.267.7
Code generation60.745.642.952.756.470.4
Math49.929.722.833.037.950.7
Factual knowledge38.446.749.858.643.163.4
Multilingual56.766.557.466.766.671.0
Robustness61.138.440.651.064.569.3

A graph of a diagram Description automatically generated with medium confidence

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.

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 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.

The table below highlights improvements on instruction following,
structure output, and reasoning of the new release on our internal
benchmark datasets.

BenchmarksOriginalJune 2024 Update
Instruction Extra Hard5.76.0
Instruction Hard4.95.1
Instructions Challenge24.642.3
JSON Structure Output11.552.3
XML Structure Output14.449.8
GPQA23.730.6
MMLU68.870.9
Average21.936.7

Responsible AI Considerations

Like other language models, the Phi family of 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 the 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.

Appendix A: Benchmark Methodology

We include a brief word on methodology here - and in particular, how we
think about optimizing prompts.

In an ideal world, we would never change any prompts in our
benchmarks to ensure it is always an apples-to-apples comparison when
comparing different models. Indeed, this is our default approach, and is
the case in the vast majority of models we have run to date.

There are, however, some exceptions to this. In some cases, we see a
model that performs worse than expected on a given eval due to a
failure to respect the output format
. For example:

  • A Claude model may refuse to answer questions (for no apparent
    reason), or in coding tasks models may prefix their response with
    “Sure, I can help with that. …” which may break the parser. In such
    cases, we have opted to try different system messages (e.g. “You
    must always respond to a question” or “Get to the point!”).

  • With LLaMA-1 models, we observed that few shots actually hurt model
    performance. In this case we did allow running the benchmarks with
    0-shots for all cases.

  • We have tools to convert between chat and completions APIs. When
    converting a chat prompt to a completion prompt, some models have
    different keywords e.g. Human vs User. In these cases, we do allow for
    model-specific mappings for chat to completion prompts.

However, we do not:

  • Pick different few-shot examples. Few shots will always be the same
    when comparing different models.

  • Change prompt format: e.g. if it is an A/B/C/D multiple choice, we do
    not tweak this to 1/2/3/4 multiple choice.