/ Модель

Характеристики

Контекст
2 048 токенов
Параметры
1,7 млрд
Лицензия
MIT
Архитектура
phi · dense
Опубликована
10 сен 2023

phi-1

Генерация текстаТекст → текст3 профессии

Компактная языковая модель Microsoft для генерации простого кода на Python по текстовым подсказкам.

25 585скачиваний за 30 дней223лайкавеса обновлены24 ноя 2025

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Тесты пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь.

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Текст» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы. Опубликованный результат появится на этой странице.

Публичные оценки6

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

  • MATH Lvl 5

    MATH Lvl 5 Raw · выше — лучше

    Результат

    0,0098

    Open LLM v2 · архив

    Публичная таблицадругая ревизия

  • IFEval

    IFEval Raw · выше — лучше

    Результат

    0,2068

    Open LLM v2 · архив

    Публичная таблицадругая ревизия

  • GPQA

    GPQA Raw · выше — лучше

    Результат

    0,2651

    Open LLM v2 · архив

    Публичная таблицадругая ревизия

  • BBH

    BBH Raw · выше — лучше

    Результат

    0,3139

    Open LLM v2 · архив

    Публичная таблицадругая ревизия

  • MUSR

    MUSR Raw · выше — лучше

    Результат

    0,3525

    Open LLM v2 · архив

    Публичная таблицадругая ревизия

  • MMLU-PRO

    MMLU-PRO Raw · выше — лучше

    Результат

    0,1162

    Open LLM v2 · архив

    Публичная таблицадругая ревизия

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

Phi-1 — языковая модель Microsoft на архитектуре Transformer с 1,7 млрд параметров и контекстом 2048 токенов. Она предназначена прежде всего для генерации простого кода на Python; в репозитории доступны веса в формате safetensors, а для работы используется библиотека Transformers. README сообщает, что при обучении использовались фрагменты кода Python, вопросы и ответы с StackOverflow, соревновательные задачи и синтетические учебные материалы. В тесте HumanEval модель показала точность выше 50%. Модель лучше работает с запросами, оформленными как фрагмент кода с комментарием или docstring, после которого нужно продолжить код.

Phi-1 подходит для создания черновиков Python-функций и примеров, а также для подсказок при решении простых задач программирования. Английский — язык карточки; данных о поддержке других естественных языков нет. Модель часто ошибается и может неверно использовать API, особенно для библиотек за пределами небольшого набора распространённых пакетов из обучающих данных. Ответы в формате чата и на общие вопросы ненадёжны; сгенерированный код нужно проверять на корректность и безопасность. Лицензия — MIT.

Сценарии применения

  • создание черновика простой функции на Python
  • автодополнение кода Python после комментария или docstring
  • генерация учебных примеров Python
  • подготовка отправной точки для решения задач программирования

Ограничения

Модель часто генерирует некорректный код, особенно при использовании библиотек за пределами небольшого набора, представленного в обучающих данных; ответы в формате чата и на общие вопросы ненадёжны. Код может содержать ошибки безопасности, поэтому его следует проверять перед использованием.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

Model Summary

The language model Phi-1 is a Transformer with 1.3 billion parameters, specialized for basic Python coding. Its training involved a variety of data sources, including subsets of Python codes from The Stack v1.2, Q&A content from StackOverflow, competition code from code_contests, and synthetic Python textbooks and exercises generated by gpt-3.5-turbo-0301. Even though the model and the datasets are relatively small compared to contemporary Large Language Models (LLMs), Phi-1 has demonstrated an impressive accuracy rate exceeding 50% on the simple Python coding benchmark, HumanEval.

How to Use

Phi-1 has been integrated in the transformers version 4.37.0, please ensure that you are using a version equal or higher than it.

Intended Uses

Given the nature of the training data, Phi-1 is best suited for prompts using the code format:

Code Format:

def print_prime(n):
   """
   Print all primes between 1 and n
   """
   for num in range(2, n+1):
       for i in range(2, num):
           if num % i == 0:
               break
       else:
           print(num)

where the model generates the code after the comments. (Note: This is a legitimate and correct use of the else statement in Python loops.)

Notes:

  • Phi-1 is intended for code purposes. The model-generated code should be treated as a starting point rather than a definitive solution for potential use cases. Users should be cautious when employing this model in their applications.

  • Direct adoption for production coding tasks is out of the scope of this research project. As a result, Phi-1 has not been tested to ensure that it performs adequately for production-level code. Please refer to the limitation sections of this document for more details.

Sample Code

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

torch.set_default_device("cuda")

model = AutoModelForCausalLM.from_pretrained("microsoft/phi-1", torch_dtype="auto")
tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1")

inputs = tokenizer('''def print_prime(n):
   """
   Print all primes between 1 and n
   """''', return_tensors="pt", return_attention_mask=False)

outputs = model.generate(**inputs, max_length=200)
text = tokenizer.batch_decode(outputs)[0]
print(text)

Limitations of Phi-1

  • Limited Scope: 99.8% of the Python scripts in our fine-tuning dataset use only the packages "typing, math, random, collections, datetime, itertools". If the model generates Python scripts that utilize other packages, we strongly recommend users manually verify all API uses.

  • Replicate Scripts Online: As our model is trained on Python scripts found online, there is a small chance it may replicate such scripts, especially if they appear repetitively across different online sources.

  • Generate Inaccurate Code: The model frequently generates incorrect code. We suggest that users view these outputs as a source of inspiration rather than definitive solutions.

  • Unreliable Responses to Alternate Formats: Despite appearing to comprehend instructions in formats like Q&A or chat, our models often respond with inaccurate answers, even when seeming confident. Their capabilities with non-code formats are significantly more limited.

  • Limitations on Natural Language Comprehension. As a coding bot, Phi-1's main focus is to help with coding-related questions. While it may have some natural language comprehension capabilities, its primary function is not to engage in general conversations or demonstrate common sense like a general AI assistant. Its strength lies in providing assistance and guidance in the context of programming and software development.

  • Potential Biases: Phi-1, like other AI models, is trained on web and synthetic data. This data can contain biases and errors that might affect the AI's performance. Biases could stem from various sources like unbalanced representation, stereotypes, or controversial opinions present in the training data. As a result, the model might sometimes generate responses that reflect these biases or errors.

Warning about Security Risks

When leveraging Phi-1, it's paramount to be vigilant. The model, though powerful, can inadvertently introduce security vulnerabilities in the generated code. Examples include, but are not limited to:

  • Directory Traversal: The code might fail to implement safe checks against directory traversal attacks, potentially allowing unauthorized access to sensitive files on your system.

  • Injection Attacks: There could be lapses in escaping strings properly, making the application susceptible to SQL, OS commands, or other injection attacks.

  • Misunderstanding Requirements: The model might sometimes misunderstand or oversimplify user requirements, leading to incomplete or insecure solutions.

  • Lack of Input Validation: In some cases, the model might neglect to incorporate input validation or sanitize user inputs, opening doors to attacks like Cross-Site Scripting (XSS).

  • Insecure Defaults: The model might recommend or generate code with insecure default settings, such as weak password requirements or unencrypted data transmissions.

  • Failure in Error Handling: Improper error handling can inadvertently reveal sensitive information about the system or the application's internal workings.

Given these potential pitfalls, and others not explicitly mentioned, it's essential to thoroughly review, test, and verify the generated code before deploying it in any application, especially those that are security-sensitive. Always consult with security experts or perform rigorous penetration testing when in doubt.

Training

Model

  • Architecture: a Transformer-based model with next-word prediction objective

  • Training tokens: 54B tokens (7B unique tokens)

  • Precision: fp16

  • GPUs: 8 A100

  • Training time: 6 days

Software

License

The model is licensed under the MIT license.

Citation

@article{gunasekar2023textbooks,
  title={Textbooks Are All You Need},
  author={Gunasekar, Suriya and Zhang, Yi and Aneja, Jyoti and Mendes, Caio C{\'e}sar Teodoro and Del Giorno, Allie and Gopi, Sivakanth and Javaheripi, Mojan and Kauffmann, Piero and de Rosa, Gustavo and Saarikivi, Olli and others},
  journal={arXiv preprint arXiv:2306.11644},
  year={2023}
}

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

Data Summary

https://huggingface.co/microsoft/phi-1/blob/main/data_summary_card.md

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм

Можно запустить

Подбираем GPU…

Класс архитектуры
PhiForCausalLM
Ревизия весов
d4c0adc

0 моделей