Технічний КЕРІВНИЦТВО

Суміш експертів LoRA

Mixture of LoRA experts is a family of fine-tuning methods that attach several small low-rank adapters, called LoRA experts, to a frozen language model and use a learned router to decide how much each adapter contributes for each input.

Послухайте цей посібникШІ-розказаний · ~7 min

На цій сторінці8 min read
  1. Огляд
  2. Ключові висновки
  3. Глибоке занурення
  4. Count the parameters in a small LoRA mixture
  5. Реалізація в реальному світі
  6. Майбутнє суміші експертів LoRA
  7. Застосування на практиці
  8. Джерела та подальше читання
  9. Продовжуйте досліджувати
  10. Часті запитання

Огляд

It combines the low cost of LoRA with the specialization of mixture-of-experts models, so one base model can handle many tasks while training under 1% of its parameters.

Ключові висновки

  1. A mixture of LoRA experts attaches several low-rank adapters to a frozen model and uses a router to weight them for each input.
  2. LoRA cut trainable parameters 10,000-fold and GPU memory threefold compared with fully fine-tuning GPT-3 175B, according to its 2021 paper.
  3. Cohere's 2023 study matched full fine-tuning while updating under 1% of an 11-billion-parameter model using lightweight experts.
  4. Dynamic routing prevents merging adapters into the base weights, so mixtures of LoRA experts add some inference cost that a single merged LoRA avoids.
  5. Load-balancing losses keep routers from sending nearly all tokens to a few experts, a failure called expert collapse.

Глибоке занурення

Mixture of LoRA experts combines two established ideas. The first is LoRA, low-rank adaptation, introduced by Edward Hu and colleagues in June 2021. Instead of retraining all the weights of a large model, LoRA freezes them and learns a small correction for selected weight matrices, written as the product of two thin matrices. For GPT-3 175B, the LoRA paper reports 10,000 times fewer trainable parameters and three times less GPU memory than full fine-tuning, with no added inference delay once the correction is merged into the weights. The second idea is the mixture of experts (MoE): a model contains several sub-networks, called experts, and a small gating network, or router, chooses which ones to use for each input. Noam Shazeer and colleagues showed in 2017 that sparsely gated MoE layers with up to thousands of experts could raise model capacity more than 1,000-fold with little extra computation.

A mixture of LoRA experts uses LoRA adapters as the experts. Step by step: a pretrained model is frozen; at chosen layers, usually the attention projections or the feed-forward block, several LoRA adapters are attached side by side; a router, typically one small linear layer followed by a softmax, reads the current token's hidden state and outputs a weight for each adapter; each adapter computes its low-rank correction; and the corrections are added to the frozen layer's output in proportion to the router's weights. With sparse routing, only the top one or two adapters are computed for each token. During training only the adapters and router are updated.

The reason to do this rather than train one bigger adapter is interference. When one adapter is trained on a mixture of very different tasks, such as coding, translation and arithmetic, the tasks compete for the same few parameters. Separate experts let different kinds of input use different parameters. LoRAMoE, posted in December 2023 by Shihan Dou and colleagues, targeted a specific version of this problem: scaling up instruction data can damage the world knowledge a model learned in pretraining. It splits its LoRA experts so some focus on preserving existing knowledge and others on new tasks, and reports gains on downstream tasks while retaining stored knowledge.

The approach developed through several papers. In September 2023 Ted Zadouri and colleagues at Cohere, in "Pushing Mixture of Experts to the Limit", built mixtures of lightweight experts including LoRA-based ones and updated less than 1% of an 11-billion-parameter model, outperforming standard parameter-efficient methods and matching full fine-tuning on instruction tuning. LoraHub, posted in July 2023 by Chengsong Huang and colleagues, took a different route: it combines LoRA modules already trained on separate tasks, choosing fixed mixing weights from a few examples of a new task with a gradient-free search. MixLoRA, from April 2024, added top-k routed LoRA experts inside feed-forward blocks plus separate LoRA adapters on attention, with a load-balancing loss so the router does not overuse a few experts. In April 2024 Xun Wu, Shaohan Huang and Furu Wei described Mixture of LoRA Experts (MoLE), which learns gating over existing trained LoRAs and was tested in both language and vision-and-language settings.

Compared with the alternatives, the trade-offs are clear. Full fine-tuning updates every weight and adapts best, but needs far more memory and produces a full copy of the model per task. A single LoRA adapter is cheapest to train and serve but can struggle with many mixed tasks. Merging several LoRAs by simple weighted addition, a common shortcut, is free at inference but, according to the MoLE paper, can weaken the base model's generation and blur each LoRA's distinct behavior. Keeping separate adapters and switching between them by hand works when the task is known in advance, but requires an outside decision about which adapter to use. A learned router makes that choice automatically, per token, at the cost of extra machinery.

The approach has real limitations. Routers can collapse, sending almost all tokens to one or two experts and leaving the others untrained, which is why methods such as MixLoRA add load-balancing losses. Input-dependent routing removes one of LoRA's main advantages: because the mixture changes token by token, the adapters cannot be merged into the base weights ahead of time, so inference does extra work. Batching requests that use different adapters complicates serving, which is the problem S-LoRA addresses. Reported gains are mostly self-reported on academic benchmarks with specific base models, and results vary with the number of experts, rank, routing method and which layers receive experts.

In practice the costs are modest. Each LoRA expert adds two thin matrices per adapted weight matrix, so even several experts usually total well under the 1% of model parameters reported in the Cohere work. Training fits on the same hardware used for ordinary LoRA fine-tuning, plus a little memory for the extra adapters and router. The main engineering decisions are how many experts to use, their rank, whether routing is dense or top-k, and which layers to adapt. Serving many adapters efficiently benefits from systems built for it; S-LoRA reports serving thousands of concurrent adapters with up to four times the throughput of naive approaches in Hugging Face PEFT and vLLM.

04Спрацьований приклад

Count the parameters in a small LoRA mixture

  1. Take one attention projection of size 4,096 by 4,096, which has about 16.8 million frozen weights.

  2. Add one LoRA adapter of rank 8: A is 8 by 4,096 and B is 4,096 by 8, giving 65,536 trainable parameters.

  3. Make it a mixture of 4 such experts: 4 times 65,536 is 262,144 parameters.

  4. Add a router that maps the 4,096-dimensional input to 4 gate scores: 4,096 times 4 is 16,384 parameters.

  5. Total trainable parameters: 278,528, about 1.7% of the frozen matrix.

  6. With top-2 routing, compute two adapter corrections per token instead of four and compare the extra work with the base matrix multiply.

Що це показує

A concrete budget showing that four experts plus a router cost under 2% of one weight matrix, and that top-2 routing halves adapter compute. Check it by building the layer in PyTorch, freezing W0 and summing numel() over parameters with requires_grad set.

Реалізація в реальному світі

Cohere researchers showed in 2023 that a mixture of LoRA experts trained on instructions updated less than 1% of an 11-billion-parameter model yet performed on par with full fine-tuning.

LoRAMoE (December 2023) dedicates some LoRA experts to preserving a model's stored world knowledge while others learn new tasks, reducing the forgetting caused by large instruction datasets.

LoraHub (COLM 2024) combines LoRA modules trained on different tasks to tackle unseen Big-Bench Hard tasks from a few examples, without gradients or extra parameters.

MixLoRA adds top-k routed LoRA experts to a frozen model's feed-forward layers and reports about 9% higher multi-task accuracy than standard parameter-efficient methods.

S-LoRA, a serving system built for many adapters, serves thousands of concurrent LoRA adapters with up to four times the throughput of naive serving in Hugging Face PEFT and vLLM.

Майбутнє суміші експертів LoRA

Research since 2023 has explored several directions at once: jointly trained LoRA mixtures for instruction tuning (Cohere, September 2023), mixtures that protect pretrained knowledge (LoRAMoE, December 2023), composition of independently trained adapters (LoraHub, published at COLM 2024, and MoLE, April 2024) and sparse top-k LoRA experts with load balancing (MixLoRA, 2024). Serving infrastructure has advanced in parallel, with S-LoRA showing that thousands of adapters can share one base model on the same hardware. Open problems include stable routing without expert collapse, principled choices for the number and rank of experts, fair comparison across papers that use different base models and benchmarks, and keeping latency low when adapters cannot be merged into the base weights. LoraHub's authors proposed a platform where users share trained LoRA modules for reuse on new tasks; whether shared adapter libraries with automatic routing become common practice, or whether single well-trained adapters and larger base models remain simpler and good enough, is still an open question that depends on evidence from production use rather than benchmarks alone.

Застосування на практиці

Чому це важливо

  • Вартість і бюджет. Архітектурні рішення збільшують продуктивність і експлуатаційні витрати протягом багатьох років.
  • Чіткіші рішення. Технічна освіта допомагає командам вибрати правильний стек, а не лише найновіший.
  • Контроль якості. Кращий інженерний вибір зменшує проблеми з надійністю у виробництві.

Зверніть увагу на

  • Оптимізація одного тесту може приховати ширші слабкі сторони системи.
  • Витрати на інфраструктуру та обслуговування часто недооцінюються.
  • Прогалини в безпеці та спостережуваності можуть зростати в міру ускладнення систем.

Наступні кроки

  1. Визначте цільові показники затримки, якості та вартості перед впровадженням.
  2. Тест за реалістичних умов навантаження та даних.
  3. Моніторинг інструментів на наявність помилок, дрейфу та впливу користувача.
  4. Перед масштабуванням підготуйте шляхи відкату та реагування на інциденти.

Джерела та подальше читання

  1. arXivLoRA: Low-Rank Adaptation of Large Language Models
  2. arXivOutrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer
  3. arXiv (Cohere)Pushing Mixture of Experts to the Limit: Extremely Parameter Efficient MoE for Instruction Tuning
  4. arXivLoRAMoE: Alleviate World Knowledge Forgetting in Large Language Models via MoE-Style Plugin
  5. arXiv (COLM 2024)LoraHub: Efficient Cross-Task Generalization via Dynamic LoRA Composition
  6. arXivСуміш експертів LoRA
  7. arXivMixLoRA: Enhancing Large Language Models Fine-Tuning with LoRA-based Mixture of Experts
  8. arXivS-LoRA: Serving Thousands of Concurrent LoRA Adapters

Продовжуйте досліджувати

Безплатний розсилок

Отримуйте щоденне зведення новин про ШІ

Три перевірені історії про ШІ щоробочого ранку, написані простою мовою. Безплатно назавжди, без реклами.

Один лист щотижня з понеділка по п'ятницю. Відписатися в один клік. Ми ніколи не продаємо та не передаємо вашу адресу.

Перевір себе

Take the Mixture of LoRA Experts quiz

Миттєва зворотна связь на кожну відповідь та сертифікат із перевіреним ідентифікатором, яким можна поділитися, після проходження курсу.

Розпочати вікторину

Підтримайте безплатну освіту у сфері ШІ. AI Understanding — це некомерційна організація 501(c)(3) — без реклами, без платних стін, назавжди. Зробіть пожертву

Часті запитання

What is Mixture of LoRA Experts?

Mixture of LoRA experts is a family of fine-tuning methods that attach several small low-rank adapters, called LoRA experts, to a frozen language model and use a learned router to decide how much each adapter contributes for each input. It combines the low cost of LoRA with the specialization of mixture-of-experts models, so one base model can handle many tasks while training under 1% of its parameters.

Про що йдеться в розділі «LoRA» на сайті Mixture of LoRA Experts?

LoRA означає Low-Rank Adaptation: він заморожує базову модель і тренує компактні низькорангові матриці, які дешево коригують поведінку.

Яка робота мережі шлюзів/маршрутизаторів у MoLE?

Маршрутизатор створює вагові коефіцієнти для доступних експертів LoRA, вибираючи та змішуючи їх для кожного входу (і часто для кожного шару чи маркера).

Чому MoLE часто краще, ніж тренувати один адаптер для багатьох змішаних завдань?

Окремі експерти уникають катастрофічного забування та перешкод у виконанні завдань, які виникають, коли один адаптер повинен освоювати багато суперечливих навичок одночасно.

Під час навчання MoLE, що зазвичай відбувається з попередньо підготовленими вагами базової моделі?

Хребет залишається замороженим; лише невеликі експерти LoRA та мережа стробування отримують градієнтні оновлення.

У моделях дифузійних зображень, яку проблему допомагає вирішити ієрархічне/пошарове стробування в MoLE?

Пошарове стробування визначає, наскільки сильно кожен адаптер впливає на кожен рівень, дозволяючи кільком концептуальним LoRA поєднуватися без домінування одного.

Продовжуйте вчитися

Пов'язані посібники

Інші посібники, вибрані для цієї теми

Отримайте безкоштовний сертифікат зі ШІКороткий безкоштовний курс та іспит. Безкоштовно, без картки. Близько 2,5 години.Почати безкоштовно →