Публикация была переведена автоматически. Исходный язык: Английский
В статье описано, что есть на платформе Hugging Face, какие бывают архитектуры моделей, как запустить языковую модель на своём компьютере и как улучшить её работу. Цифры взяты из официальной документации по состоянию на декабрь 2026 года.
Что такое Hugging Face
Hugging Face — американская компания и одноимённая платформа, на которой публикуются модели машинного обучения, наборы данных и демонстрационные приложения. Платформу называют «GitHub для машинного обучения»: каждый проект хранится как Git-репозиторий с историей версий, а публичные репозитории открыты для всех.
Компанию основали в 2016 году Клеман Деланг, Жюльен Шомон и Тома Вольф, штаб-квартира находится в Нью-Йорке. Первым продуктом был чат-бот для подростков. После того как его модель выложили в открытый доступ, компания переключилась на платформу для машинного обучения.
В сентябре 2026 года Nvidia объявила о соглашении купить Hugging Face. Закрытие сделки ожидается в первой половине 2027 года после одобрения регуляторов.
На платформе размещено более 3 млн моделей, 1 млн наборов данных и 2 млн приложений, эти числа приведены в документации. Сведения о компании взяты из статьи в Википедии.
Что есть на платформе
Центральная часть платформы называется Hub. Регистрация и скачивание публичных моделей бесплатны, платными бывают вычисления на серверах платформы.
Models — репозитории с весами моделей, конфигурацией и описанием. Веса — числовые параметры модели, подобранные при обучении. Отсюда модель скачивают, чтобы запустить у себя. Применение обученной модели к новым данным называется инференсом.
Datasets — наборы данных для обучения и проверки моделей. Содержимое набора можно просмотреть в браузере.
Spaces — хостинг демонстрационных приложений. Автор модели выкладывает интерфейс, и посетитель пробует модель в браузере без установки. Приложения бывают трёх видов: Gradio, Docker и статический HTML.
Inference Providers — вызов моделей через API без собственного оборудования. Запросы обслуживают сторонние компании-провайдеры. В указателе документации заявлено более 200 тыс. моделей; при этом через API доступны только те, которые обслуживает хотя бы один провайдер. Для чат-моделей есть интерфейс, совместимый с API OpenAI: в существующей программе меняют адрес, ключ доступа и имя модели.
Inference Endpoints — запуск выбранной модели на выделенных серверах, которыми управляет платформа.
Кроме того, на платформе есть каталог задач Tasks с примерами моделей и данных и таблицы сравнения моделей Leaderboards.
Какие бывают архитектуры моделей
Архитектура — это устройство нейросети: из каких слоёв она состоит и как через них проходят данные. От архитектуры зависит, какие задачи модель решает и какой программой её запускают.
Большинство моделей на Hub построены на архитектуре «трансформер». Её предложили исследователи Google в 2017 году в статье Attention Is All You Need. Перед обработкой текст разбивается на токены — слова, части слов или отдельные символы. Основа трансформера — механизм внимания: обрабатывая очередной токен, модель учитывает доступные ей токены последовательности и сама определяет, какие из них важны. По курсу Hugging Face, трансформеры делятся на три вида.

На схеме показано одно вычисление внимания. Из вектора каждого токена получают три вектора: запрос, ключ и значение. Матрицы Q, K и V составлены из этих векторов для всех токенов. Скалярные произведения запросов и ключей дают оценки близости токенов. Функция softmax превращает оценки в веса, сумма которых по строке равна единице. Новый вектор токена — сумма значений, взятых с этими весами. Деление на √d_k, где d_k — размерность ключей, не даёт оценкам расти вместе с размерностью.
Энкодеры читают текст целиком: внимание видит все слова предложения сразу, слева и справа от текущего. Текст такие модели не генерируют. Их применяют для классификации, распознавания именованных сущностей и поиска ответа в готовом тексте. Примеры — BERT, DistilBERT, ModernBERT. На энкодерах часто строят модели эмбеддингов: они превращают текст в числовой вектор, по которому тексты сравнивают по смыслу.
Декодеры работают авторегрессионно: каждый токен видит себя и предыдущие токены, а модель предсказывает следующий. Это архитектура генерации текста. Большинство современных больших языковых моделей — декодеры. Примеры — Llama, Gemma, SmolLM, а также семейства GPT и Qwen.
Энкодер-декодеры соединяют обе части: энкодер читает входной текст целиком, декодер по нему пишет новый. Их используют там, где ответ зависит от конкретного входа: перевод, краткий пересказ, ответы на вопросы. Примеры — T5, BART, Marian. По той же схеме устроена модель распознавания речи Whisper.

Маска M задаёт, какие позиции доступны вниманию. Она прибавляется к оценкам до softmax: разрешённым позициям соответствует ноль, запрещённым — минус бесконечность, и их вес становится нулевым. Энкодер не скрывает будущие токены, декодер скрывает. В энкодер-декодере три отдельных внимания: энкодера, декодера и декодера к выходу энкодера. В формулах x — входная последовательность, y — выходная, h_i — вектор токена i, P — вероятность, знак ∏ — произведение.
У трансформеров есть разновидность Mixture of Experts (MoE, «смесь экспертов»). В такой модели часть слоёв заменена набором «экспертов» — небольших нейросетей, а маршрутизатор решает, каким экспертам отдать каждый токен. По описанию Hugging Face, на каждый токен работает только часть экспертов, поэтому вычислений нужно меньше, чем плотной модели того же размера. При этом в память загружаются все эксперты, и требования к памяти определяются полным числом параметров.
Архитектура сети, способ генерации и тип данных — разные характеристики: одна модель может быть трансформером, использовать MoE и работать с изображениями.
Диффузионные модели создают изображения, видео и звук. Они начинают со случайного шума и за несколько шагов превращают его в изображение по текстовому описанию. Число шагов зависит от модели: от одного-четырёх до нескольких десятков. Пример — Stable Diffusion; близкий подход использует FLUX. Для них предназначена библиотека Diffusers.
Свёрточные сети и Vision Transformer работают с изображениями. Свёрточные сети, например ResNet и ConvNeXT, просматривают картинку небольшими окнами. Vision Transformer — это трансформер для изображений: он делит картинку на фрагменты и обрабатывает их как последовательность токенов.
Мультимодальные модели принимают данные разных типов. CLIP сопоставляет изображения и тексты в общем пространстве. Визуально-языковые модели получают картинку вместе с вопросом и отвечают текстом.
Модели пространства состояний — альтернатива трансформеру. Одна из них, Mamba, обходится без механизма внимания. Её разработали для длинных последовательностей, на которых трансформер требует слишком много вычислений.
Для чата обычно берут декодер, обученный вести диалог, для поиска по документам — модель эмбеддингов. Программа локального запуска должна поддерживать архитектуру выбранной модели, иначе файл не загрузится.
Как читать карточку модели
У каждой модели есть карточка — файл README в репозитории. Он состоит из блока метаданных и текста, где автор описывает назначение и ограничения модели, параметры обучения, использованные данные и результаты оценки.
Лицензия в метаданных определяет, разрешено ли коммерческое использование. Список языков показывает, на каких языках модель работает. Тип задачи говорит, для чего она предназначена: генерация текста, классификация, распознавание речи. Поле базовой модели указывает, на чём основан этот вариант, и помогает найти дообученные и квантизованные версии.
В названиях языковых моделей встречаются пометки base и instruct. Базовая модель только продолжает текст. Instruct-модель дополнительно обучена выполнять инструкции и вести диалог, для чата и ассистентов нужна именно она.
Файлы части публичных моделей можно скачать только по запросу; такой режим называется gated. Пользователь входит в аккаунт, открывает страницу модели и отправляет запрос. Автор получает имя пользователя и адрес почты и открывает доступ автоматически или после ручной проверки.
Веса распространяются в двух основных форматах. Safetensors — формат для transformers и других библиотек Python, он хранит только тензоры. GGUF — бинарный формат, оптимизированный для быстрой загрузки. Он хранит тензоры вместе с метаданными, разработан автором llama.cpp и используется в llama.cpp, Ollama и LM Studio. Для запуска на домашнем компьютере обычно ищут GGUF-версию модели.
У чат-моделей есть шаблон чата. Он задаёт, как список сообщений превращается в строку с управляющими токенами. С неверными управляющими токенами качество ответов резко падает. Программы локального запуска берут шаблон из файла модели сами. В transformers его применяет чат-pipeline, а при прямом вызове модели форматирование задаёт разработчик.
Квантизация и память
Квантизация — запись весов модели меньшим числом бит. Файл становится меньше, и модель удаётся запустить на менее мощном компьютере. Качество ответов при этом может снижаться, особенно при сильном сжатии; насколько — зависит от модели и проверяется на своих задачах.
Типы квантизации GGUF по документации Hub:
| Тип | Бит на вес |
| F16 | 16 |
| Q8_0 | 8,5 |
| Q6_K | 6,5625 |
| Q5_K | 5,5 |
| Q4_K | 4,5 |
| IQ4_XS | 4,25 |
| Q3_K | 3,4375 |
| Q2_K | 2,625 |
Строка F16 — исходные 16-битные веса без сжатия, она приведена для сравнения. В именах файлов встречаются обозначения вроде Q4_K_M. Суффикс S, M или L указывает вариант квантизации: часть тензоров в нём хранится с большей или меньшей точностью, поэтому различаются и размер файла, и качество.
Чтобы оценить объём весов, число параметров умножают на число бит на вес и делят на 8. Для модели на 8 млрд параметров в Q4_K это около 4,5 ГБ, для модели на 27 млрд параметров в IQ4_XS — около 14,3 ГБ. Точный размер файла указан на странице репозитория.
Памяти нужно больше, чем занимает файл. Кроме весов она расходуется на контекст — текст, который модель учитывает в одном запросе: системное сообщение, историю диалога, вопрос и ответ. Чем длиннее контекст, тем больше памяти. Когда модель не помещается в видеопамять целиком, llama.cpp может считать часть слоёв на процессоре, но генерация при этом замедляется. При нехватке памяти уменьшают контекст или берут модель меньшего размера.
В библиотеке transformers квантизацию выполняет bitsandbytes. По сравнению с 16-битными весами загрузка в 8 бит сокращает их объём вдвое, в 4 бита — в четыре раза. На видеокартах NVIDIA для 4-битного режима нужно поколение Pascal или новее.
С чего начать
Для первого знакомства установка не нужна: достаточно открыть раздел Spaces и попробовать несколько моделей в браузере.
Следующий шаг — регистрация на huggingface.co. Аккаунт нужен для моделей с доступом по запросу и для публикации своих работ. В настройках аккаунта создаётся токен доступа — ключ, которым программы подтверждают личность пользователя. С токенами текста у него общее только название.
Из терминала с платформой работает утилита hf, она устанавливается вместе с пакетом huggingface_hub. Утилита выполняет вход по токену и скачивает с Hub репозитории целиком или отдельные файлы.
В Python самый короткий путь к модели — функция pipeline из библиотеки transformers. При её вызове указывают тип задачи и имя модели, и функция скачивает веса и готовит модель к работе. Затем ей передают запрос. Если он оформлен как список сообщений с ролями, шаблон чата применяется автоматически; обычную строку модель просто продолжает. Для первых опытов этого хватает, больше настроек дают классы моделей и токенизаторов той же библиотеки.
Локальный запуск
Локальный запуск означает, что модель работает на компьютере пользователя, а не на сервере провайдера. После скачивания модель работает без интернета и без платы за запросы. Данные остаются на компьютере, если сама программа и подключённые к ней инструменты не отправляют их наружу. Ограничения — объём памяти и скорость генерации.
Hub поддерживает список локальных программ.
llama.cpp — движок на C/C++ для моделей в формате GGUF. Он работает на процессоре и на видеокарте, включает консольный чат и сервер с API, совместимым с OpenAI. Устанавливается через менеджеры пакетов: winget в Windows, Homebrew в macOS и Linux. Модель указывают именем репозитория на Hub, и программа сама скачивает файл.
Ollama — утилита командной строки с фоновой службой и локальным API. Она запускает GGUF-модели с Hub по адресу вида «hf.co/автор/репозиторий», к которому можно добавить нужную квантизацию. Если квантизация не указана, берётся Q4_K_M, когда она есть в репозитории.
LM Studio — настольное приложение с графическим интерфейсом: поиск моделей, чат и локальный сервер в одном окне. Подходит тем, кто не работает в терминале.
Для первого запуска LM Studio устанавливают с официального сайта. В разделе поиска моделей выбирают instruct-модель в формате GGUF и скачивают вариант, для которого памяти хватает с запасом. Затем в окне чата выбирают скачанную модель, дожидаются её загрузки в память и задают первый вопрос.
В том же списке есть MLX LM для компьютеров Apple с процессорами Apple Silicon, а также vLLM и SGLang — серверы для обслуживания многих запросов на видеокартах.
Программы включаются в настройках аккаунта, раздел Local Apps. После этого на странице модели в меню Use this model показываются совместимые программы и готовая команда запуска. Её остаётся скопировать в терминал.
Библиотеки
Hugging Face развивает набор открытых библиотек, полный перечень приведён в указателе документации. Для запуска модели в настольном приложении они не нужны; библиотеки требуются при разработке собственных программ.
Запуск моделей. Основная библиотека — transformers: она загружает, запускает и обучает модели на PyTorch. tokenizers отвечает за быстрое разбиение текста на токены, safetensors — за безопасный формат хранения весов. transformers.js запускает модели прямо в браузере.
Данные и поиск. datasets загружает и обрабатывает наборы данных. sentence-transformers работает с моделями эмбеддингов для поиска по смыслу и с моделями переранжирования, которые уточняют порядок найденных документов.
Обучение. peft реализует дообучение малым числом параметров, включая LoRA. trl содержит готовые циклы обучения языковых моделей. accelerate распределяет обучение по нескольким видеокартам, bitsandbytes квантизует модели в 8 и 4 бита, optimum ускоряет обучение и инференс.
Платформа и приложения. huggingface_hub — Python-клиент Hub, вместе с ним ставится утилита командной строки hf. gradio строит веб-интерфейсы на Python, smolagents — агентов. lighteval оценивает языковые модели, trackio ведёт учёт экспериментов. Для генерации изображений, видео и звука предназначена diffusers.
Способы улучшить локальную модель
Способы перечислены от дешёвого к дорогому. Первые семь не меняют веса модели и не требуют обучения.
Выбор модели и квантизации. Сильнее всего на качество влияет сама модель. Сравнивают несколько моделей, которые помещаются в память и поддерживают нужный язык, и выбирают по результатам на своих задачах. Число параметров само по себе качество не определяет: небольшая модель, обученная под задачу, может оказаться лучше крупной универсальной.
Параметры генерации. Температура и top-p управляют случайностью ответа: при низких значениях ответы стабильнее, при высоких разнообразнее. Длина контекста определяет, сколько текста модель видит одновременно, лимит токенов — наибольшую длину ответа. У моделей с режимом рассуждений его отключают на простых задачах, чтобы ускорить ответ.
Шаблон чата. Запросы должны форматироваться шаблоном самой модели. Если ответы неожиданно ухудшились, первым делом проверяют, тот ли шаблон применяется.
Системный промпт и примеры. В системном промпте задают роль модели и формат ответа. Несколько образцов «вопрос — ответ» в запросе показывают модели, что от неё требуется, без какого-либо обучения.
Поиск по документам (RAG). Документы делят на фрагменты и для каждого вычисляют эмбеддинг. Фрагменты, близкие по смыслу к вопросу пользователя, передают модели вместе с вопросом. Так модель отвечает по сведениям, которых не было в её обучающих данных. Эмбеддинги считают библиотекой sentence-transformers.
Инструменты и агенты. Модель запрашивает вызов функции с аргументами, а программа выполняет вычисление, поиск или запуск кода. Результат добавляют в диалог, и модель использует его в ответе. Для построения агентов у Hugging Face есть библиотека smolagents.
Структурированный вывод. Ответ ограничивается схемой JSON или грамматикой. Движок на каждом шаге разрешает только те токены, которые не нарушают схему, поэтому ответ можно разбирать программой. В llama.cpp для этого служат грамматики. Ответ всё равно проверяют: он может оборваться на лимите токенов, а правильная структура не гарантирует правильных значений.
Дообучение. На собственных примерах обучается адаптер LoRA, который меняет поведение модели. Этому способу посвящён следующий раздел.
Дистилляция. Малая модель обучается воспроизводить ответы большой. Цель — приблизиться к её качеству при меньших требованиях к памяти.
Поиск по документам помогает, когда модели не хватает сведений. Инструменты помогают, когда она ошибается в вычислениях. Дообучение применяют, когда нужно изменить стиль или формат ответов либо научить модель узкой задаче.
Результат каждого шага проверяют на одном и том же наборе задач с заранее заданным критерием, например долей правильных ответов. При случайном выборе токенов ответы меняются от запуска к запуску, поэтому проверку повторяют несколько раз и сравнивают средние значения. Для оценки языковых моделей у Hugging Face есть библиотека lighteval.
Дообучение: LoRA и QLoRA
Полное дообучение меняет все веса модели и требует много памяти. Методы PEFT обучают лишь малую часть параметров модели или небольшое число добавленных. По документации PEFT, это снижает затраты на вычисления и хранение, а качество может быть сопоставимо с полным дообучением.
Самый распространённый метод — LoRA. Изменение весов задают двумя небольшими матрицами низкого ранга, а исходная матрица весов не меняется. Результат обучения — отдельный файл-адаптер, который во много раз меньше модели. Адаптер работает только с той базовой моделью, на которой обучен. Его подключают к ней при запуске или объединяют с ней, тогда он не замедляет генерацию.
Ранг LoRA задаёт размер матриц: чем он меньше, тем меньше обучаемых параметров. Коэффициент масштабирования определяет силу влияния адаптера. Список модулей указывает, куда добавляют слои LoRA; обычно это блоки внимания.
QLoRA соединяет LoRA с квантизацией: базовая модель загружается в 4 битах, а поверх неё обучаются веса адаптера. Так модель дообучают на видеокарте, в память которой полная версия не помещается. По документации bitsandbytes, в 8- и 4-битном режиме обучаются только дополнительные параметры. Среди других вариантов метода в документации перечислены rsLoRA и DoRA.
Сам цикл обучения выполняет библиотека TRL. Обучение на готовых примерах (SFT) используют чаще всего: модели показывают пары «запрос — правильный ответ». Метод DPO обучает на парах из предпочтительного и отклонённого ответа. GRPO относится к обучению с подкреплением. Отдельный класс отвечает за дистилляцию знаний из другой модели.
Сначала на Hub проверяют, нет ли готовой модели или адаптера под задачу. Затем собирают примеры, откладывают часть для проверки и оценивают на ней ответы базовой модели. После обучения адаптера результат сравнивают с базовой моделью на тех же задачах. Адаптер объединяют с моделью и при необходимости преобразуют её в GGUF средствами llama.cpp.
Дообучение не гарантирует улучшения. На малом числе примеров адаптер может не дать прироста, а при обучении на ответах другой модели он воспроизводит и её ошибки. Поэтому сравнение с базовой моделью на отложенных задачах обязательно.
Модели для казахского языка
На Hub есть модели, адаптированные под казахский язык. Институт ISSAI при Назарбаев Университете публикует коллекцию Qwen3.5 Kazakh: instruct-модели и базовую модель, дообученную на расширенном словаре. В коллекции три варианта с обозначениями 4B, 9B и 35B-A3B; точное число параметров и размер файлов указаны на странице каждой модели.
Другие модели с поддержкой казахского находятся фильтром по языку на странице моделей Hub. Язык указывается в метаданных карточки модели.
Порядок действий для начинающего
- Зарегистрироваться на huggingface.co и попробовать несколько моделей в Spaces без установки.
- Определить объём видеопамяти или оперативной памяти компьютера.
- Выбрать модель и квантизацию, которые помещаются в эту память.
- Установить Ollama, LM Studio или llama.cpp и запустить модель.
- Составить набор типичных вопросов с правильными ответами и измерить на нём качество.
- Настроить параметры генерации и системный промпт, повторить измерение.
- Подключить поиск по своим документам или инструменты, если ошибки связаны с нехваткой сведений или вычислениями.
- Переходить к дообучению, когда предыдущие шаги исчерпаны.
This article covers what the Hugging Face platform offers, which model architectures exist, how to run a language model on your own computer, and how to improve its output. The figures come from the official documentation as of December 2026.
What Hugging Face is
Hugging Face is an American company and the platform of the same name, where machine learning models, datasets and demo applications are published. The platform is often called “the GitHub of machine learning”: every project is stored as a Git repository with version history, and public repositories are open to everyone.
The company was founded in 2016 by Clément Delangue, Julien Chaumond and Thomas Wolf and is headquartered in New York. Its first product was a chatbot for teenagers. After the chatbot's model was released as open source, the company switched to building a platform for machine learning.
In September 2026 Nvidia announced an agreement to acquire Hugging Face. The deal is expected to close in the first half of 2027, after regulatory approval.
The platform hosts more than 3 million models, 1 million datasets and 2 million applications; these numbers are given in the documentation. The facts about the company are taken from the Wikipedia article.
What the platform offers
The central part of the platform is called the Hub. Signing up and downloading public models are free; computation on the platform's servers may be paid.
Models are repositories with model weights, configuration and a description. Weights are the numeric parameters of a model, fitted during training. This is where a model is downloaded from to be run locally. Applying a trained model to new data is called inference.
Datasets are collections of data for training and evaluating models. The contents of a dataset can be viewed in the browser.
Spaces is hosting for demo applications. A model's author publishes an interface, and a visitor tries the model in the browser without installing anything. Applications come in three kinds: Gradio, Docker and static HTML.
Inference Providers lets you call models through an API without your own hardware. Requests are served by third-party provider companies. The documentation index claims more than 200,000 models, but only those served by at least one provider are available through the API. For chat models there is an interface compatible with the OpenAI API: in an existing program you change the address, the access key and the model name.
Inference Endpoints runs a chosen model on dedicated servers managed by the platform.
The platform also has Tasks, a catalogue of tasks with example models and data, and Leaderboards, tables that compare models.
Which model architectures exist
An architecture is the structure of a neural network: which layers it consists of and how data passes through them. The architecture determines which tasks a model solves and which program runs it.

Most models on the Hub are built on the transformer architecture. Google researchers proposed it in 2017 in the paper Attention Is All You Need. Before processing, text is split into tokens: words, parts of words or single characters. The core of a transformer is the attention mechanism: while processing a token, the model takes into account the tokens of the sequence available to it and decides by itself which of them matter. According to the Hugging Face course, transformers fall into three kinds.
The diagram shows a single attention computation. Three vectors are derived from the vector of each token: a query, a key and a value. The matrices Q, K and V are made of these vectors for all tokens. Dot products of queries and keys give similarity scores between tokens. The softmax function turns the scores into weights that sum to one in each row. The new vector of a token is the sum of the values taken with these weights. Dividing by √d_k, where d_k is the dimension of the keys, keeps the scores from growing with the dimension.
Encoders read the whole text: attention sees all the words of a sentence at once, to the left and to the right of the current one. These models do not generate text. They are used for classification, named entity recognition and finding an answer in a given text. Examples are BERT, DistilBERT and ModernBERT. Embedding models are often built on encoders: they turn a text into a numeric vector, and texts are then compared by meaning through these vectors.
Decoders work autoregressively: each token sees itself and the preceding tokens, and the model predicts the next one. This is the architecture for text generation. Most modern large language models are decoders. Examples are Llama, Gemma and SmolLM, as well as the GPT and Qwen families.
Encoder-decoders combine both parts: the encoder reads the whole input text, and the decoder writes a new text from it. They are used where the answer depends on a specific input: translation, summarization, question answering. Examples are T5, BART and Marian. The Whisper speech recognition model follows the same scheme.

The mask M sets which positions attention may use. It is added to the scores before softmax: allowed positions get zero, forbidden ones get minus infinity, and their weight becomes zero. An encoder does not hide future tokens; a decoder does. An encoder-decoder has three separate attentions: the encoder's, the decoder's, and the decoder's attention to the encoder output. In the formulas, x is the input sequence, y is the output sequence, h_i is the vector of token i, P is a probability, and the sign ∏ is a product.
Transformers have a variety called Mixture of Experts (MoE). In such a model some layers are replaced by a set of “experts”, small neural networks, and a router decides which experts receive each token. According to the Hugging Face description, only some of the experts work on each token, so less computation is needed than in a dense model of the same size. All the experts are still loaded into memory, so memory requirements are set by the total number of parameters.
Network architecture, generation method and data type are separate properties: one model can be a transformer, use MoE and work with images.
Diffusion models create images, video and audio. They start from random noise and turn it into an image that matches a text description in several steps. The number of steps depends on the model: from one to four up to several dozen. An example is Stable Diffusion; FLUX uses a similar approach. The Diffusers library is intended for them.
Convolutional networks and the Vision Transformer work with images. Convolutional networks, such as ResNet and ConvNeXT, scan a picture with small windows. The Vision Transformer is a transformer for images: it splits a picture into patches and processes them as a sequence of tokens.
Multimodal models accept data of different types. CLIP matches images and texts in a shared space. Vision-language models receive a picture together with a question and answer in text.
State space models are an alternative to the transformer. One of them, Mamba, does without the attention mechanism. It was developed for long sequences, on which a transformer needs too much computation.
For chat, a decoder trained for dialogue is the usual choice; for document search, an embedding model. The program used for local inference must support the architecture of the chosen model, otherwise the file will not load.
How to read a model card
Every model has a card, the README file in its repository. It consists of a metadata block and a text in which the author describes the purpose and limitations of the model, the training parameters, the data used and the evaluation results.
The license in the metadata determines whether commercial use is allowed. The list of languages shows which languages the model works with. The task type says what the model is meant for: text generation, classification, speech recognition. The base model field shows what this variant is built on and helps to find fine-tuned and quantized versions.
Names of language models often carry the labels base and instruct. A base model only continues text. An instruct model is additionally trained to follow instructions and hold a dialogue, and it is the one needed for chat and assistants.
The files of some public models can be downloaded only on request; this mode is called gated. The user signs in, opens the model page and sends a request. The author receives the user's name and email address and grants access automatically or after a manual review.
Weights are distributed in two main formats. Safetensors is the format for transformers and other Python libraries; it stores only tensors. GGUF is a binary format optimized for fast loading. It stores tensors together with metadata, was developed by the author of llama.cpp and is used in llama.cpp, Ollama and LM Studio. To run a model on a home computer, people usually look for its GGUF version.
Chat models have a chat template. It defines how a list of messages is turned into a string with control tokens. With the wrong control tokens the quality of answers drops sharply. Programs for local inference take the template from the model file themselves. In transformers the chat pipeline applies it, and when the model is called directly the developer is responsible for the formatting.
Quantization and memory
Quantization means storing model weights with fewer bits. The file gets smaller, and the model can be run on a less powerful computer. The quality of answers may drop, especially with strong compression; how much depends on the model and has to be checked on your own tasks.
GGUF quantization types according to the Hub documentation:
| Type | Bits per weight |
| F16 | 16 |
| Q8_0 | 8.5 |
| Q6_K | 6.5625 |
| Q5_K | 5.5 |
| Q4_K | 4.5 |
| IQ4_XS | 4.25 |
| Q3_K | 3.4375 |
| Q2_K | 2.625 |
The F16 row is the original 16-bit weights without compression; it is given for comparison. File names contain labels such as Q4_K_M. The suffix S, M or L marks a variant of the quantization: some tensors in it are stored with higher or lower precision, so both file size and quality differ.
To estimate the size of the weights, multiply the number of parameters by the bits per weight and divide by 8. For a model with 8 billion parameters in Q4_K this is about 4.5 GB; for a model with 27 billion parameters in IQ4_XS, about 14.3 GB. The exact file size is shown on the repository page.
More memory is needed than the file takes. Besides the weights, memory is spent on the context: the text the model takes into account in one request, that is, the system message, the dialogue history, the question and the answer. The longer the context, the more memory. When a model does not fit into video memory entirely, llama.cpp can compute some of the layers on the CPU, but generation becomes slower. If memory runs short, the context is reduced or a smaller model is chosen.
In the transformers library quantization is done by bitsandbytes. Compared with 16-bit weights, loading in 8 bits halves their size, and loading in 4 bits cuts it to a quarter. On NVIDIA graphics cards the 4-bit mode requires the Pascal generation or newer.
Where to start
A first look requires no installation: it is enough to open the Spaces section and try a few models in the browser.
The next step is to sign up at huggingface.co. An account is needed for gated models and for publishing your own work. An access token is created in the account settings; it is a key that programs use to confirm the user's identity. It shares only its name with text tokens.
From the terminal, the platform is handled by the hf utility, which is installed together with the huggingface_hub package. The utility signs in with a token and downloads whole repositories or single files from the Hub.
In Python the shortest way to a model is the pipeline function from the transformers library. It is called with a task type and a model name, and the function downloads the weights and prepares the model for work. Then a request is passed to it. If the request is a list of messages with roles, the chat template is applied automatically; a plain string is simply continued by the model. This is enough for first experiments, and the model and tokenizer classes of the same library give more settings.
Local inference
Local inference means that the model runs on the user's computer and not on a provider's server. Once downloaded, the model works without the internet and without a fee per request. The data stays on the computer, unless the program itself or the tools connected to it send the data out. The limits are the amount of memory and the speed of generation.
The Hub maintains a list of local applications.
llama.cpp is an engine written in C/C++ for models in the GGUF format. It runs on the CPU and on the GPU and includes a console chat and a server with an OpenAI-compatible API. It is installed through package managers: winget on Windows, Homebrew on macOS and Linux. The model is specified by the name of its repository on the Hub, and the program downloads the file by itself.
Ollama is a command-line utility with a background service and a local API. It runs GGUF models from the Hub by an address of the form “hf.co/author/repository”, to which the required quantization can be added. If no quantization is given, Q4_K_M is used when the repository has it.
LM Studio is a desktop application with a graphical interface: model search, chat and a local server in one window. It suits those who do not work in a terminal.
For a first run, LM Studio is installed from the official website. In the model search section the user picks an instruct model in the GGUF format and downloads a variant that leaves memory to spare. Then, in the chat window, the user selects the downloaded model, waits until it is loaded into memory and asks the first question.
The same list includes MLX LM for Apple computers with Apple Silicon processors, as well as vLLM and SGLang, servers for handling many requests on GPUs.
The applications are enabled in the account settings, in the Local Apps section. After that, the Use this model menu on a model page shows the compatible applications and a ready command to run the model. All that is left is to copy it into the terminal.
Libraries
Hugging Face develops a set of open-source libraries; the full list is given in the documentation index. They are not needed to run a model in a desktop application; the libraries are required when developing your own programs.
Running models. The main library is transformers: it loads, runs and trains models on PyTorch. tokenizers handles fast splitting of text into tokens, and safetensors provides a safe format for storing weights. transformers.js runs models directly in the browser.
Data and search. datasets loads and processes datasets. sentence-transformers works with embedding models for semantic search and with reranking models, which refine the order of the documents found.
Training. peft implements fine-tuning with a small number of parameters, including LoRA. trl contains ready-made training loops for language models. accelerate distributes training across several GPUs, bitsandbytes quantizes models to 8 and 4 bits, and optimum speeds up training and inference.
Platform and applications. huggingface_hub is the Python client of the Hub; the hf command-line utility is installed with it. gradio builds web interfaces in Python, and smolagents builds agents. lighteval evaluates language models, and trackio keeps track of experiments. diffusers is intended for generating images, video and audio.
Ways to improve a local model
The methods are listed from cheap to expensive. The first seven do not change the model's weights and require no training.
Choosing a model and a quantization. The model itself affects quality the most. Several models that fit into memory and support the required language are compared, and the choice is made by the results on your own tasks. The number of parameters alone does not determine quality: a small model trained for a task can turn out better than a large general-purpose one.
Generation parameters. Temperature and top-p control the randomness of the answer: at low values answers are more stable, at high values more varied. The context length determines how much text the model sees at once, and the token limit sets the maximum length of the answer. In models with a reasoning mode, the mode is switched off on simple tasks to speed up the answer.
Chat template. Requests must be formatted with the model's own template. If answers suddenly get worse, the first thing to check is whether the right template is applied.
System prompt and examples. The system prompt sets the model's role and the format of the answer. A few “question and answer” samples in the request show the model what is required of it, without any training.
Document search (RAG). Documents are split into chunks, and an embedding is computed for each. The chunks closest in meaning to the user's question are passed to the model together with the question. This way the model answers from information that was not in its training data. Embeddings are computed with the sentence-transformers library.
Tools and agents. The model requests a function call with arguments, and the program performs a calculation, a search or a code run. The result is added to the dialogue, and the model uses it in its answer. For building agents, Hugging Face has the smolagents library.
Structured output. The answer is constrained by a JSON schema or a grammar. At each step the engine allows only the tokens that do not break the schema, so the answer can be parsed by a program. In llama.cpp grammars serve this purpose. The answer is still checked: it can be cut off at the token limit, and a correct structure does not guarantee correct values.
Fine-tuning. A LoRA adapter that changes the model's behaviour is trained on your own examples. The next section is devoted to this method.
Distillation. A small model is trained to reproduce the answers of a large one. The goal is to approach its quality with lower memory requirements.
Document search helps when the model lacks information. Tools help when it makes mistakes in calculations. Fine-tuning is used when the style or format of the answers has to change, or when the model has to learn a narrow task.
The result of each step is checked on the same set of tasks with a criterion defined in advance, for example the share of correct answers. When tokens are sampled randomly, answers change from run to run, so the check is repeated several times and the averages are compared. For evaluating language models, Hugging Face has the lighteval library.
Fine-tuning: LoRA and QLoRA
Full fine-tuning changes all the weights of a model and requires a lot of memory. PEFT methods train only a small part of the model's parameters or a small number of added ones. According to the PEFT documentation, this lowers the cost of computation and storage, and the quality can be comparable to full fine-tuning.
The most widespread method is LoRA. The change in the weights is defined by two small low-rank matrices, and the original weight matrix stays unchanged. The result of training is a separate adapter file that is many times smaller than the model. An adapter works only with the base model it was trained on. It is attached to that model at launch or merged into it, in which case it does not slow down generation.
The LoRA rank sets the size of the matrices: the smaller it is, the fewer trainable parameters there are. The scaling factor determines how strongly the adapter acts. The list of modules shows where LoRA layers are added; usually these are the attention blocks.
QLoRA combines LoRA with quantization: the base model is loaded in 4 bits, and the adapter weights are trained on top of it. This is how a model is fine-tuned on a graphics card whose memory cannot hold the full version. According to the bitsandbytes documentation, only the additional parameters are trained in 8-bit and 4-bit mode. Among other variants of the method, the documentation lists rsLoRA and DoRA.
The training loop itself is run by the TRL library. Training on ready examples (SFT) is used most often: the model is shown pairs of a request and the correct answer. The DPO method trains on pairs of a preferred and a rejected answer. GRPO belongs to reinforcement learning. A separate class handles distilling knowledge from another model.
First, the Hub is checked for a ready model or adapter for the task. Then examples are collected, part of them is set aside for testing, and the answers of the base model are evaluated on that part. After the adapter is trained, the result is compared with the base model on the same tasks. The adapter is merged with the model and, if needed, the model is converted to GGUF with the llama.cpp tools.
Fine-tuning does not guarantee an improvement. With few examples an adapter may give no gain, and when trained on the answers of another model it reproduces that model's mistakes as well. This is why the comparison with the base model on held-out tasks is mandatory.
Models for the Kazakh language
The Hub has models adapted to the Kazakh language. The ISSAI institute at Nazarbayev University publishes the Qwen3.5 Kazakh collection: instruct models and a base model further trained with an extended vocabulary. The collection has three variants labelled 4B, 9B and 35B-A3B; the exact number of parameters and the file sizes are given on each model's page.
Other models that support Kazakh can be found with the language filter on the Hub's models page. The language is given in the metadata of the model card.
Steps for a beginner
- Sign up at huggingface.co and try a few models in Spaces without installing anything.
- Find out how much video memory or RAM the computer has.
- Choose a model and a quantization that fit into this memory.
- Install Ollama, LM Studio or llama.cpp and run the model.
- Put together a set of typical questions with correct answers and measure quality on it.
- Adjust the generation parameters and the system prompt, then repeat the measurement.
- Add search over your own documents or tools if the mistakes come from missing information or from calculations.
- Move on to fine-tuning when the previous steps are exhausted.
Комментарии 4
Недавние Популярные