Files changed (1) hide show
  1. README.md +402 -5
README.md CHANGED
@@ -1,5 +1,402 @@
1
- ---
2
- license: other
3
- license_name: jamba-open-model-license
4
- license_link: https://www.ai21.com/jamba-open-model-license/
5
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: jamba-open-model-license
4
+ license_link: https://www.ai21.com/jamba-open-model-license/
5
+ ---
6
+ # Model Information
7
+
8
+ Built with hybrid SSM-Transformer architecture, the Jamba 1.6 family of models outperform other open, instruction-following foundation models on quality, speed, and long context performance, and rival leading closed models on quality. As open models, Jamba Mini 1.6 (12B active/52B total) and Jamba Large 1.6 (94B active/398B total) are available for private deployment, either in VPC or on-premise, and demonstrate superior performance on the kind of long context tasks that matter most to enterprises, such as RAG workflows and grounded question answering across lengthy documents.
9
+
10
+ The models are released under the Jamba Open Model License, a permissive license allowing full research use and commercial use under the license terms.
11
+
12
+ If you need to license the model for your needs, talk to us.
13
+
14
+ For more details of this model, see the release blog post.
15
+ ## Model Details
16
+
17
+ - **Developed by:** [AI21](https://www.ai21.com)
18
+ - **Model type:** Joint Attention and Mamba (Jamba)
19
+ - **License:** [Jamba Open Model License](https://www.ai21.com/licenses/jamba-open-model-license)
20
+ - **Context length:** 256K
21
+ - **Knowledge cutoff date:** March 5, 2024
22
+ - **Supported languages:** English, Spanish, French, Portuguese, Italian, Dutch, German, Arabic and Hebrew
23
+
24
+
25
+ # Usage
26
+ ## Prerequisites
27
+
28
+ In order to run optimized Mamba implementations, you first need to install `mamba-ssm` and `causal-conv1d`:
29
+ ```bash
30
+ pip install mamba-ssm causal-conv1d>=1.2.0
31
+ ```
32
+ You also have to have the model on a CUDA device.
33
+
34
+
35
+ ## Run the model with vLLM
36
+
37
+ The recommended way to perform efficient inference with Jamba Large 1.6 is using [vLLM](https://docs.vllm.ai/en/latest/). First, make sure to install vLLM (version 0.5.4 or higher is required)
38
+ ```bash
39
+ pip install vllm>=0.5.4
40
+ ```
41
+
42
+ In the example below, `number_gpus` should match the number of GPUs you want to deploy Jamba Large 1.6 on. A minimum of 2 80GB GPUs is required.
43
+
44
+ ```python
45
+ from vllm import LLM, SamplingParams
46
+ from transformers import AutoTokenizer
47
+
48
+ model = "ai21labs/AI21-Jamba-Large-1.6"
49
+ number_gpus = 2
50
+
51
+ llm = LLM(model=model,
52
+ max_model_len=200*1024,
53
+ tensor_parallel_size=number_gpus)
54
+
55
+ tokenizer = AutoTokenizer.from_pretrained(model)
56
+
57
+ messages = [
58
+ {"role": "system", "content": "You are an ancient oracle who speaks in cryptic but wise phrases, always hinting at deeper meanings."},
59
+ {"role": "user", "content": "Hello!"},
60
+ ]
61
+
62
+ prompts = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
63
+
64
+ sampling_params = SamplingParams(temperature=0.4, top_p=0.95, max_tokens=100)
65
+ outputs = llm.generate(prompts, sampling_params)
66
+
67
+ generated_text = outputs[0].outputs[0].text
68
+ print(generated_text)
69
+ #Output: Seek and you shall find. The path is winding, but the journey is enlightening. What wisdom do you seek from the ancient echoes?
70
+ ```
71
+
72
+ With the default BF16 precision on 2 80GB A100 GPUs and default vLLM configuration, you'll be able to perform inference on prompts up to 200K tokens long. On more than 2 80GB GPUs, you can easily fit the full 256K context.
73
+
74
+ <u>Note:</u> vLLM's `main` branch has some memory utilization improvements specific to the Jamba architecture that allow using the full 256K context length on 2 80 GPUs. You can [build vLLM from source](https://docs.vllm.ai/en/latest/getting_started/installation.html#build-from-source) if you wish to make use of them.
75
+
76
+ ### ExpertsInt8 quantization
77
+ We've developed an innovative and efficient quantization technique, [ExpertsInt8](https://www.ai21.com/blog/announcing-jamba-model-family#:~:text=Like%20all%20models%20in%20its%20size%20class%2C%20Jamba%201.6%20Large%20can%E2%80%99t%20be%20loaded%20in%20full%20(FP32)%20or%20half%20(FP16/BF16)%20precision%20on%20a%20single%20node%20of%208%20GPUs.%20Dissatisfied%20with%20currently%20available%20quantization%20techniques%2C%20we%20developed%20ExpertsInt8%2C%20a%20novel%20quantization%20technique%20tailored%20for%20MoE%20models.), designed for MoE models deployed in vLLM, including Jamba models. Using it, you'll be able to deploy Jamba Large 1.6 on a single 80GB GPU.
78
+
79
+ In order to use ExpertsInt8, you need to use vllm version 0.5.5 or higher: `pip install vllm>=0.5.5`
80
+
81
+ With default vLLM configuration, you can fit prompts up to 100K on a single 80GB A100 GPU:
82
+ ```python
83
+ import os
84
+ os.environ['VLLM_FUSED_MOE_CHUNK_SIZE']='32768' # This is a workaround a bug in vLLM's fused_moe kernel
85
+
86
+ from vllm import LLM
87
+ llm = LLM(model="ai21labs/AI21-Jamba-Large-1.6",
88
+ max_model_len=100*1024,
89
+ quantization="experts_int8")
90
+ ```
91
+
92
+
93
+ ## Run the model with `transformers`
94
+
95
+ The following example loads Jamba Large 1.6 to the GPU in BF16 precision, uses optimized [FlashAttention2](https://github.com/Dao-AILab/flash-attention) and Mamba kernels, and parallelizes the model across multiple GPUs using [accelerate](https://huggingface.co/docs/accelerate/index). Note that in half precision (FP16/BF16), Jamba Large 1.6 is too large to fit on a single 80GB GPU, so you'll need at least 2 such GPUs.
96
+
97
+ ```python
98
+ import torch
99
+ from transformers import AutoModelForCausalLM, AutoTokenizer
100
+
101
+ model = AutoModelForCausalLM.from_pretrained("ai21labs/AI21-Jamba-Large-1.6",
102
+ torch_dtype=torch.bfloat16,
103
+ attn_implementation="flash_attention_2",
104
+ device_map="auto")
105
+
106
+ tokenizer = AutoTokenizer.from_pretrained("ai21labs/AI21-Jamba-Large-1.6")
107
+
108
+ messages = [
109
+ {"role": "system", "content": "You are an ancient oracle who speaks in cryptic but wise phrases, always hinting at deeper meanings."},
110
+ {"role": "user", "content": "Hello!"},
111
+ ]
112
+
113
+ input_ids = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors='pt').to(model.device)
114
+
115
+ outputs = model.generate(input_ids, max_new_tokens=216)
116
+
117
+ # Decode the output
118
+ conversation = tokenizer.decode(outputs[0], skip_special_tokens=True)
119
+
120
+ # Split the conversation to get only the assistant's response
121
+ assistant_response = conversation.split(messages[-1]['content'])[1].strip()
122
+ print(assistant_response)
123
+ # Output: Seek and you shall find. The path is winding, but the journey is enlightening. What wisdom do you seek from the ancient echoes?
124
+ ```
125
+
126
+ <u>Note:</u> Versions 4.44.0 and 4.44.1 of `transformers` have a bug that restricts the ability to run the Jamba architecture. Make sure you're not using these versions.
127
+
128
+ <u>Note:</u> If you're having trouble installing `mamba-ssm` and `causal-conv1d` for the optimized Mamba kernels, you can run Jamba Large 1.6 without them, at the cost of extra latency. In order to do that, add the kwarg `use_mamba_kernels=False` when loading the model via `AutoModelForCausalLM.from_pretained()`.
129
+
130
+ <details><summary><strong>Load the model in 8-bit</strong></summary>
131
+
132
+ **Using 8-bit precision, it is possible to fit up to 140K sequence length on a single 80GB GPU.** You can easily quantize the model to 8-bit using [bitsandbytes](https://huggingface.co/docs/bitsandbytes/index). In order to not degrade model quality, we recommend to exclude the Mamba blocks from the quantization:
133
+
134
+ ```python
135
+ from transformers import AutoModelForCausalLM, BitsAndBytesConfig
136
+ quantization_config = BitsAndBytesConfig(load_in_8bit=True,
137
+ llm_int8_skip_modules=["mamba"])
138
+ model = AutoModelForCausalLM.from_pretrained("ai21labs/AI21-Jamba-Large-1.6",
139
+ torch_dtype=torch.bfloat16,
140
+ attn_implementation="flash_attention_2",
141
+ quantization_config=quantization_config)
142
+ ```
143
+
144
+ </details>
145
+
146
+ <details><summary><strong>Load the model on CPU</strong></summary>
147
+
148
+ If you don't have access to a GPU, you can also load and run Jamba Large 1.6 on a CPU. Note this will result in poor inference performance.
149
+
150
+ ```python
151
+ from transformers import AutoModelForCausalLM
152
+ model = AutoModelForCausalLM.from_pretrained("ai21labs/AI21-Jamba-Large-1.6",
153
+ use_mamba_kernels=False)
154
+ ```
155
+ </details>
156
+ <br>
157
+ <br>
158
+
159
+ # Model features
160
+
161
+ ## Tool use with Jamba
162
+ Jamba Large 1.6 supports tool use capabilities in accordance with Huggingface's tool use API. The tools defined by the user are inserted into a dedicated section in the chat template which the model was trained to recognize.
163
+
164
+ Given a conversation that contains tools, the model can output content, tool invocations or both.
165
+
166
+ <details><summary><strong>Tool usage example</strong></summary>
167
+
168
+
169
+ ```python
170
+ from transformers import AutoTokenizer
171
+
172
+ tokenizer = AutoTokenizer.from_pretrained("ai21labs/AI21-Jamba-Large-1.6")
173
+
174
+ messages = [
175
+ {
176
+ "role": "user",
177
+ "content": "What's the weather like right now in Jerusalem and in London?"
178
+ }
179
+ ]
180
+
181
+ tools = [
182
+ {
183
+ 'type': 'function',
184
+ 'function': {
185
+ 'name': 'get_current_weather',
186
+ 'description': 'Get the current weather',
187
+ 'parameters': {
188
+ 'type': 'object',
189
+ 'properties': {
190
+ 'location': {'type': 'string', 'description': 'The city and state, e.g. San Francisco, CA'},
191
+ 'format': {'type': 'string', 'enum': ['celsius', 'fahrenheit'], 'description': 'The temperature unit to use. Infer this from the users location.'}
192
+ },
193
+ 'required': ['location', 'format']
194
+ }
195
+ }
196
+ }
197
+ ]
198
+
199
+ prompt = tokenizer.apply_chat_template(
200
+ messages,
201
+ tools=tools,
202
+ tokenize=False,
203
+ )
204
+ ```
205
+ Output:
206
+ ```
207
+ <tool_calls>[
208
+ {"name": "get_current_weather", "arguments": {"location": "Jerusalem", "format": "celsius"}},
209
+ {"name": "get_current_weather", "arguments": {"location": "celsius", "format": "celsius"}}
210
+ ]</tool_calls>
211
+ ```
212
+
213
+ </details>
214
+
215
+
216
+ <details><summary><strong>Feeding back tool responses into the model</strong></summary>
217
+
218
+ Now that the model has called the tools, we need to feed the tool responses back to the model. In the next call, send the assistant message with the `tool_messages` field, as shown below, along with additional `tool` messages (in the corresponding order) that contain the tool outputs.
219
+
220
+ The `arguments` field for each tool call can be either a dict or a JSON string.
221
+
222
+ ```python
223
+ from transformers import AutoTokenizer
224
+
225
+ tokenizer = AutoTokenizer.from_pretrained("ai21labs/AI21-Jamba-Large-1.6")
226
+
227
+ # Note that you must send the tool responses in the same order as the model called the tools:
228
+ messages = [
229
+ {
230
+ "role": "user",
231
+ "content": "What's the weather like right now in Jerusalem and in London?"
232
+ },
233
+ {
234
+ "role": "assistant",
235
+ "content": null,
236
+ "tool_calls": [
237
+ {
238
+ "name": "get_current_weather",
239
+ "arguments": "{\"location\": \"Jerusalem\", \"format\": \"celsius\"}"
240
+ },
241
+ {
242
+ "name": "get_current_weather",
243
+ "arguments": "{\"location\": \"London\", \"format\": \"celsius\"}"
244
+ }
245
+ ]
246
+ },
247
+ {
248
+ "role": "tool",
249
+ "content": "The weather in Jerusalem is 18 degrees celsius."
250
+ },
251
+ {
252
+ "role": "tool",
253
+ "content": "The weather in London is 8 degrees celsius."
254
+ }
255
+ ]
256
+
257
+ tool_use_prompt = tokenizer.apply_chat_template(
258
+ messages,
259
+ tools=tools,
260
+ tokenize=False,
261
+ )
262
+ ```
263
+ example output:
264
+ ```
265
+ The weather in Jerusalem is currently 18 degrees Celsius. In London, it is 8 degrees Celsius.
266
+ ```
267
+
268
+ </details>
269
+
270
+
271
+ ## Fine-tuning examples
272
+
273
+ The examples below use the `SFTTrainer` from [huggingface/trl](https://github.com/huggingface/trl), so ensure it's installed:
274
+ ```bash
275
+ pip install trl
276
+ ```
277
+
278
+ ## Full Fine-tuning example
279
+ To train a full finetune using AWS multi nodes and FSDP configuration, follow the instructions here [hf-finetune-sagemaker](https://github.com/AI21Labs/hf-finetune-sagemaker)
280
+
281
+ ## LoRA example
282
+
283
+ Here is an example of fine-tuning with LoRA PEFT, in bfloat16 (requires ~130GB GPU RAM, so e.g. 2xA100 80GB):
284
+
285
+ ```python
286
+ import torch
287
+ from transformers import AutoTokenizer, AutoModelForCausalLM
288
+ from datasets import load_dataset
289
+ from trl import SFTTrainer, SFTConfig
290
+ from peft import LoraConfig
291
+
292
+ tokenizer = AutoTokenizer.from_pretrained("ai21labs/AI21-Jamba-Large-1.6")
293
+ model = AutoModelForCausalLM.from_pretrained(
294
+ "ai21labs/AI21-Jamba-Large-1.6",
295
+ device_map="auto",
296
+ torch_dtype=torch.bfloat16,
297
+ attn_implementation="flash_attention_2",
298
+ )
299
+
300
+ lora_config = LoraConfig(
301
+ r=8,
302
+ target_modules=[
303
+ "embed_tokens",
304
+ "x_proj", "in_proj", "out_proj", # mamba
305
+ "gate_proj", "up_proj", "down_proj", # mlp
306
+ "q_proj", "k_proj", "v_proj", "o_proj", # attention
307
+ ],
308
+ task_type="CAUSAL_LM",
309
+ bias="none",
310
+ )
311
+
312
+ dataset = load_dataset("philschmid/dolly-15k-oai-style", split="train")
313
+ training_args = SFTConfig(
314
+ output_dir="/dev/shm/results",
315
+ logging_dir="./logs",
316
+ num_train_epochs=2,
317
+ per_device_train_batch_size=4,
318
+ learning_rate=1e-5,
319
+ logging_steps=10,
320
+ gradient_checkpointing=True,
321
+ max_seq_length=4096,
322
+ save_steps=100,
323
+ )
324
+ trainer = SFTTrainer(
325
+ model=model,
326
+ tokenizer=tokenizer,
327
+ args=training_args,
328
+ peft_config=lora_config,
329
+ train_dataset=dataset,
330
+ )
331
+ trainer.train()
332
+ ```
333
+
334
+ Note that the dataset in the example uses conversational format (with `messages` column), so `SFTTrainer` automatically applies Jamba's chat-template as explained in [TRL docs](https://huggingface.co/docs/trl/main/en/sft_trainer#dataset-format-support).
335
+
336
+ ## QLoRA example
337
+
338
+ To fit fine-tuning on a single 80GB GPU, you can levarage [QLoRA](https://arxiv.org/abs/2305.14314) which combines LoRA with the frozen model quantized to 4-bit:
339
+
340
+ ```python
341
+ import torch
342
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
343
+ from datasets import load_dataset
344
+ from trl import SFTTrainer, SFTConfig
345
+ from peft import LoraConfig
346
+
347
+ tokenizer = AutoTokenizer.from_pretrained("ai21labs/AI21-Jamba-Large-1.6")
348
+ quantization_config = BitsAndBytesConfig(
349
+ load_in_4bit=True,
350
+ bnb_4bit_quant_type="nf4",
351
+ bnb_4bit_compute_dtype=torch.bfloat16,
352
+ )
353
+ model = AutoModelForCausalLM.from_pretrained(
354
+ "ai21labs/AI21-Jamba-Large-1.6",
355
+ device_map="auto",
356
+ quantization_config=quantization_config,
357
+ torch_dtype=torch.bfloat16,
358
+ attn_implementation="flash_attention_2",
359
+ )
360
+ lora_config = LoraConfig(
361
+ r=8,
362
+ target_modules=[
363
+ "embed_tokens", "x_proj", "in_proj", "out_proj", # mamba
364
+ "gate_proj", "up_proj", "down_proj", # mlp
365
+ "q_proj", "k_proj", "v_proj", "o_proj", # attention
366
+ ],
367
+ task_type="CAUSAL_LM",
368
+ bias="none",
369
+ )
370
+
371
+ dataset = load_dataset("philschmid/dolly-15k-oai-style", split="train")
372
+ training_args = SFTConfig(
373
+ output_dir="./results",
374
+ logging_dir="./logs",
375
+ num_train_epochs=2,
376
+ per_device_train_batch_size=8,
377
+ learning_rate=1e-5,
378
+ logging_steps=1,
379
+ gradient_checkpointing=True,
380
+ gradient_checkpointing_kwargs={"use_reentrant": False},
381
+ save_steps=100,
382
+ max_seq_length=4096,
383
+ )
384
+ trainer = SFTTrainer(
385
+ model=model,
386
+ tokenizer=tokenizer,
387
+ args=training_args,
388
+ peft_config=lora_config,
389
+ train_dataset=dataset,
390
+ )
391
+ trainer.train()
392
+ ```
393
+
394
+ Note: the above example reqiures the `bitsandbytes` package for the 4-bit quantization:
395
+ ```bash
396
+ pip install bitsandbytes
397
+ ```
398
+
399
+ # About AI21
400
+
401
+ AI21 builds reliable, practical, and scalable AI solutions for the enterprise. The Jamba models are available in the [AI21 Studio](https://www.ai21.com/studio) and in leading cloud partners.
402
+ To learn more about how Jamba Mini 1.6 and Jamba Large 1.6 can bring real world value to your organization, let’s talk.