optimum-rbln 0.8.2a4__py3-none-any.whl → 0.8.2a6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of optimum-rbln might be problematic. Click here for more details.

Files changed (64) hide show
  1. optimum/rbln/__init__.py +44 -0
  2. optimum/rbln/__version__.py +2 -2
  3. optimum/rbln/configuration_utils.py +4 -0
  4. optimum/rbln/ops/kv_cache_update.py +5 -0
  5. optimum/rbln/ops/linear.py +7 -0
  6. optimum/rbln/transformers/__init__.py +48 -0
  7. optimum/rbln/transformers/modeling_attention_utils.py +252 -0
  8. optimum/rbln/transformers/models/__init__.py +35 -14
  9. optimum/rbln/transformers/models/decoderonly/__init__.py +2 -2
  10. optimum/rbln/transformers/models/decoderonly/configuration_decoderonly.py +214 -45
  11. optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py +122 -205
  12. optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +569 -366
  13. optimum/rbln/transformers/models/gemma/__init__.py +2 -2
  14. optimum/rbln/transformers/models/gemma/configuration_gemma.py +9 -1
  15. optimum/rbln/transformers/models/gemma/modeling_gemma.py +13 -1
  16. optimum/rbln/transformers/models/gemma3/configuration_gemma3.py +7 -5
  17. optimum/rbln/transformers/models/gemma3/modeling_gemma3.py +82 -59
  18. optimum/rbln/transformers/models/gpt2/__init__.py +2 -2
  19. optimum/rbln/transformers/models/gpt2/configuration_gpt2.py +31 -3
  20. optimum/rbln/transformers/models/gpt2/gpt2_architecture.py +6 -7
  21. optimum/rbln/transformers/models/gpt2/modeling_gpt2.py +16 -1
  22. optimum/rbln/transformers/models/idefics3/modeling_idefics3.py +2 -2
  23. optimum/rbln/transformers/models/llama/__init__.py +2 -2
  24. optimum/rbln/transformers/models/llama/configuration_llama.py +9 -1
  25. optimum/rbln/transformers/models/llama/modeling_llama.py +13 -1
  26. optimum/rbln/transformers/models/llava/__init__.py +16 -0
  27. optimum/rbln/transformers/models/llava/configuration_llava.py +54 -0
  28. optimum/rbln/transformers/models/llava/modeling_llava.py +379 -0
  29. optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +4 -4
  30. optimum/rbln/transformers/models/mistral/__init__.py +2 -2
  31. optimum/rbln/transformers/models/mistral/configuration_mistral.py +9 -1
  32. optimum/rbln/transformers/models/mistral/mistral_architecture.py +1 -1
  33. optimum/rbln/transformers/models/mistral/modeling_mistral.py +26 -3
  34. optimum/rbln/transformers/models/opt/__init__.py +2 -2
  35. optimum/rbln/transformers/models/opt/configuration_opt.py +8 -1
  36. optimum/rbln/transformers/models/opt/modeling_opt.py +41 -1
  37. optimum/rbln/transformers/models/opt/opt_architecture.py +4 -4
  38. optimum/rbln/transformers/models/pegasus/__init__.py +17 -0
  39. optimum/rbln/transformers/models/pegasus/configuration_pegasus.py +34 -0
  40. optimum/rbln/transformers/models/pegasus/modeling_pegasus.py +69 -0
  41. optimum/rbln/transformers/models/pegasus/pegasus_architecture.py +163 -0
  42. optimum/rbln/transformers/models/phi/__init__.py +2 -2
  43. optimum/rbln/transformers/models/phi/configuration_phi.py +9 -1
  44. optimum/rbln/transformers/models/phi/modeling_phi.py +10 -1
  45. optimum/rbln/transformers/models/phi/phi_architecture.py +6 -6
  46. optimum/rbln/transformers/models/pixtral/__init__.py +16 -0
  47. optimum/rbln/transformers/models/pixtral/configuration_pixtral.py +43 -0
  48. optimum/rbln/transformers/models/pixtral/modeling_pixtral.py +318 -0
  49. optimum/rbln/transformers/models/pixtral/pixtral_architecture.py +73 -0
  50. optimum/rbln/transformers/models/qwen2/__init__.py +2 -2
  51. optimum/rbln/transformers/models/qwen2/configuration_qwen2.py +9 -1
  52. optimum/rbln/transformers/models/qwen2/modeling_qwen2.py +27 -1
  53. optimum/rbln/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py +3 -3
  54. optimum/rbln/transformers/models/qwen3/configuration_qwen3.py +2 -2
  55. optimum/rbln/transformers/models/qwen3/modeling_qwen3.py +10 -328
  56. optimum/rbln/transformers/models/qwen3/qwen3_architecture.py +0 -241
  57. optimum/rbln/transformers/models/seq2seq/configuration_seq2seq.py +0 -10
  58. optimum/rbln/transformers/models/whisper/configuration_whisper.py +1 -10
  59. optimum/rbln/transformers/models/whisper/modeling_whisper.py +5 -1
  60. optimum/rbln/utils/depreacate_utils.py +16 -0
  61. {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.8.2a6.dist-info}/METADATA +1 -1
  62. {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.8.2a6.dist-info}/RECORD +64 -51
  63. {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.8.2a6.dist-info}/WHEEL +0 -0
  64. {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.8.2a6.dist-info}/licenses/LICENSE +0 -0
@@ -12,9 +12,7 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
- from typing import Any, Dict, List, Literal, Optional, Union
16
-
17
- import rebel
15
+ from typing import Any, Dict, List, Literal, Optional, Union, get_args
18
16
 
19
17
  from ....configuration_utils import RBLNModelConfig
20
18
  from ....utils.logging import get_logger
@@ -24,11 +22,12 @@ from ...utils.rbln_quantization import RBLNQuantizationConfig
24
22
  logger = get_logger()
25
23
 
26
24
  CacheImplType = Literal["static", "sliding_window", "hybrid"]
25
+ PhaseType = Literal["prefill", "image_prefill", "decode"]
27
26
 
28
27
 
29
- class RBLNDecoderOnlyModelForCausalLMConfig(RBLNModelConfig):
28
+ class RBLNDecoderOnlyModelConfig(RBLNModelConfig):
30
29
  """
31
- Configuration class for RBLN decoder-only models for Causal Language Modeling.
30
+ Configuration class for RBLN decoder-only models.
32
31
 
33
32
  This class extends RBLNModelConfig with parameters specific to decoder-only transformer
34
33
  architectures optimized for RBLN devices. It controls aspects like attention implementation,
@@ -48,7 +47,6 @@ class RBLNDecoderOnlyModelForCausalLMConfig(RBLNModelConfig):
48
47
  quantization: Optional[Union[Dict[str, Any], RBLNQuantizationConfig]] = None,
49
48
  prefill_chunk_size: Optional[int] = None,
50
49
  kvcache_num_blocks: Optional[int] = None,
51
- decoder_batch_sizes: Optional[List[int]] = None,
52
50
  cache_impl: Optional[CacheImplType] = None,
53
51
  sliding_window: Optional[int] = None,
54
52
  sliding_window_layers: Optional[List[int]] = None,
@@ -76,20 +74,12 @@ class RBLNDecoderOnlyModelForCausalLMConfig(RBLNModelConfig):
76
74
  kvcache_block_size (Optional[int]): Sets the size (in number of tokens) of each block
77
75
  in the PagedAttention KV cache. See the "KV Cache Block Size (`kvcache_block_size`)"
78
76
  section below for details.
79
- quantization (Optional[Dict[str, Any]]): Configuration dictionary for applying model
80
- quantization. Specifies format, etc.
81
77
  prefill_chunk_size (Optional[int]): The chunk size used during the prefill phase for
82
78
  processing input sequences. Defaults to 128. Must be a positive integer
83
79
  divisible by 64. Affects prefill performance and memory usage.
84
80
  kvcache_num_blocks (Optional[int]): The total number of blocks to allocate for the
85
81
  PagedAttention KV cache. See the "KV Cache Number of Blocks (`kvcache_num_blocks`)"
86
82
  section below for details.
87
- decoder_batch_sizes (Optional[List[int]]): A list of batch sizes for which separate decoder models will be compiled.
88
- This allows the model to handle varying batch sizes efficiently during generation. If not specified,
89
- defaults to a list containing only the model's main batch size. When specifying multiple batch sizes:
90
- 1) All values must be less than or equal to the main batch size.
91
- 2) The list will be sorted in descending order (larger batch sizes first).
92
- 3) If using multiple decoders, at least one batch size should match the main batch size.
93
83
  cache_impl (Optional[CacheImplType]): Specifies the KV cache implementation strategy. Defaults to "static".
94
84
  - "static": Uses a fixed-size global KV cache for all layers, suitable for standard attention patterns.
95
85
  - "sliding_window": Implements a sliding window KV cache, where each layer maintains a local cache of recent tokens.
@@ -166,58 +156,237 @@ class RBLNDecoderOnlyModelForCausalLMConfig(RBLNModelConfig):
166
156
  self.batch_size = batch_size or 1
167
157
  if not isinstance(self.batch_size, int) or self.batch_size < 0:
168
158
  raise ValueError(f"batch_size must be a positive integer, got {self.batch_size}")
159
+ if self.batch_size > 1:
160
+ raise NotImplementedError("Batch size > 1 is not supported for RBLNDecoderOnlyModel.")
169
161
 
170
162
  self.max_seq_len = max_seq_len
171
163
  self.use_inputs_embeds = use_inputs_embeds or False
172
164
  self.use_position_ids = use_position_ids or False
173
- self.use_attention_mask = use_attention_mask
174
-
175
- npu = self.npu or rebel.get_npu_name()
176
- if npu == "RBLN-CA02":
177
- if self.use_attention_mask is False:
178
- logger.warning("Attention mask should be used with RBLN-CA02. Setting use_attention_mask to True.")
179
- self.use_attention_mask = True
180
- else:
181
- self.use_attention_mask = self.use_attention_mask or False
165
+ self.use_attention_mask = use_attention_mask or False
182
166
 
183
167
  if self.use_position_ids and not self.use_attention_mask:
184
168
  raise ValueError("Position IDs should be used with attention mask.")
185
169
 
186
- self.attn_impl = attn_impl
187
- self.kvcache_partition_len = kvcache_partition_len
188
- self.kvcache_block_size = kvcache_block_size
189
170
  self.quantization = quantization or {}
190
171
  if self.quantization and isinstance(self.quantization, dict):
191
172
  self.quantization = RBLNQuantizationConfig(**self.quantization)
192
173
 
174
+ self.attn_impl = attn_impl
175
+ self.kvcache_partition_len = kvcache_partition_len
176
+ self.kvcache_block_size = kvcache_block_size
193
177
  self.prefill_chunk_size = prefill_chunk_size or 128
194
178
  if self.prefill_chunk_size % 64 != 0 or self.prefill_chunk_size <= 0:
195
179
  raise ValueError("`prefill_chunk_size` must be a positive integer divisible by 64.")
196
180
 
197
181
  self.kvcache_num_blocks = kvcache_num_blocks
198
- self.decoder_batch_sizes = decoder_batch_sizes
199
- if self.decoder_batch_sizes is None:
200
- self.decoder_batch_sizes = [self.batch_size]
201
-
202
- if self.use_multiple_decoder:
203
- if max(self.decoder_batch_sizes) > self.batch_size:
204
- raise ValueError(
205
- f"Decoder batch size ({max(self.decoder_batch_sizes)}) must be less than or equal to the runtime batch size ({self.batch_size})."
206
- )
207
- if max(self.decoder_batch_sizes) < self.batch_size:
208
- logger.warning(
209
- f"Maximum decoder batch size ({max(self.decoder_batch_sizes)}) is less than the model's batch size ({self.batch_size}). "
210
- "Appending the model's batch size to the decoder batch size."
211
- )
212
- self.decoder_batch_sizes.append(self.batch_size)
213
-
214
- # Larger batch size should be at the beginning of the list.
215
- self.decoder_batch_sizes.sort(reverse=True)
216
-
217
182
  self.cache_impl = cache_impl or "static"
218
183
  self.sliding_window = sliding_window
219
184
  self.sliding_window_layers = sliding_window_layers or []
220
185
 
186
+ @property
187
+ def use_global_attention(self):
188
+ return self.cache_impl in ["static", "hybrid"]
189
+
190
+ @property
191
+ def use_local_attention(self):
192
+ return self.cache_impl in ["sliding_window", "hybrid"]
193
+
194
+
195
+ class RBLNDecoderOnlyModelForCausalLMConfig(RBLNDecoderOnlyModelConfig):
196
+ """
197
+ Configuration class for RBLN decoder-only models for Causal Language Modeling.
198
+
199
+ This class extends RBLNModelConfig with parameters specific to decoder-only transformer
200
+ architectures optimized for RBLN devices. It controls aspects like attention implementation,
201
+ KV cache management, and batching for inference.
202
+ """
203
+
204
+ def __init__(
205
+ self,
206
+ batch_size: Optional[int] = None,
207
+ max_seq_len: Optional[int] = None,
208
+ use_inputs_embeds: Optional[bool] = None,
209
+ use_attention_mask: Optional[bool] = None,
210
+ use_position_ids: Optional[bool] = None,
211
+ attn_impl: Optional[str] = None,
212
+ kvcache_partition_len: Optional[int] = None,
213
+ kvcache_block_size: Optional[int] = None,
214
+ quantization: Optional[Union[Dict[str, Any], RBLNQuantizationConfig]] = None,
215
+ prefill_chunk_size: Optional[int] = None,
216
+ kvcache_num_blocks: Optional[int] = None,
217
+ decoder_batch_sizes: Optional[List[int]] = None,
218
+ cache_impl: Optional[CacheImplType] = None,
219
+ sliding_window: Optional[int] = None,
220
+ sliding_window_layers: Optional[List[int]] = None,
221
+ phases: Optional[List[PhaseType]] = None,
222
+ **kwargs,
223
+ ):
224
+ """
225
+ Args:
226
+ batch_size (Optional[int]): The batch size for inference. Defaults to 1.
227
+ max_seq_len (Optional[int]): The maximum sequence length supported by the model.
228
+ If not provided, it attempts to infer from the model's configuration
229
+ (`max_position_embeddings` or `n_positions`). Must be specified if not available
230
+ in the model config.
231
+ use_inputs_embeds (Optional[bool]): Whether to use input embeddings (`inputs_embeds`)
232
+ directly instead of `input_ids`. Defaults to False. Requires the model to be
233
+ compiled with this option enabled.
234
+ use_attention_mask (Optional[bool]): Whether the model requires attention masks during
235
+ inference. This is typically determined based on the target device and model
236
+ architecture. Defaults are often set automatically based on the model and RBLN NPU.
237
+ use_position_ids (Optional[bool]): Whether to use position IDs. Defaults to False.
238
+ attn_impl (Optional[str]): Specifies the attention implementation to use.
239
+ See the "Attention Implementation (`attn_impl`)" section below for details.
240
+ kvcache_partition_len (Optional[int]): Defines the partition length for the KV cache
241
+ when using "flash_attn". See the "KV Cache Partition Length (`kvcache_partition_len`)"
242
+ section below for details.
243
+ kvcache_block_size (Optional[int]): Sets the size (in number of tokens) of each block
244
+ in the PagedAttention KV cache. See the "KV Cache Block Size (`kvcache_block_size`)"
245
+ section below for details.
246
+ quantization (Optional[Dict[str, Any]]): Configuration dictionary for applying model
247
+ quantization. Specifies format, etc.
248
+ prefill_chunk_size (Optional[int]): The chunk size used during the prefill phase for
249
+ processing input sequences. Defaults to 128. Must be a positive integer
250
+ divisible by 64. Affects prefill performance and memory usage.
251
+ kvcache_num_blocks (Optional[int]): The total number of blocks to allocate for the
252
+ PagedAttention KV cache. See the "KV Cache Number of Blocks (`kvcache_num_blocks`)"
253
+ section below for details.
254
+ decoder_batch_sizes (Optional[List[int]]): A list of batch sizes for which separate decoder models will be compiled.
255
+ This allows the model to handle varying batch sizes efficiently during generation. If not specified,
256
+ defaults to a list containing only the model's main batch size. When specifying multiple batch sizes:
257
+ 1) All values must be less than or equal to the main batch size.
258
+ 2) The list will be sorted in descending order (larger batch sizes first).
259
+ 3) If using multiple decoders, at least one batch size should match the main batch size.
260
+ cache_impl (Optional[CacheImplType]): Specifies the KV cache implementation strategy. Defaults to "static".
261
+ - "static": Uses a fixed-size global KV cache for all layers, suitable for standard attention patterns.
262
+ - "sliding_window": Implements a sliding window KV cache, where each layer maintains a local cache of recent tokens.
263
+ - "hybrid": Combines both static and sliding window approaches, allowing different layers to use different cache strategies.
264
+ The choice affects memory usage and attention patterns. When using "sliding_window" or "hybrid",
265
+ you must specify the `sliding_window` size and optionally `sliding_window_layers` for hybrid mode.
266
+ sliding_window (Optional[int]): The size of the sliding window. Defaults to None.
267
+ sliding_window_layers (Optional[List[int]]): The layers to use for the sliding window used in the hybrid model. Defaults to None.
268
+ phases (Optional[List[PhaseType]]): The phases to compile the model for. Defaults to None.
269
+ **kwargs: Additional arguments passed to the parent RBLNModelConfig.
270
+
271
+ Raises:
272
+ ValueError: If `batch_size` is not a positive integer.
273
+ ValueError: If `prefill_chunk_size` is not a positive integer divisible by 64.
274
+ ValueError: If `max_seq_len` cannot be determined and is required.
275
+ ValueError: If attention parameter constraints are violated (e.g., `max_seq_len` vs
276
+ `kvcache_partition_len` for flash attention).
277
+
278
+
279
+ Attention Implementation:
280
+ `attn_impl` determines the underlying attention mechanism used by the model.
281
+
282
+ - **`"eager"`** (Default if `kvcache_partition_len` is not set): Uses the standard PyTorch
283
+ attention implementation. Suitable for sequences up to a certain limit (e.g., 32,768 tokens).
284
+ - **`"flash_attn"`**: Utilizes an optimized Flash Attention implementation, beneficial for
285
+ longer sequences and potentially faster execution. Requires `max_seq_len` to be at least
286
+ 8,192. If `kvcache_partition_len` is specified, `attn_impl` automatically defaults
287
+ to `"flash_attn"`. When using `"flash_attn"`, `kvcache_block_size` must equal
288
+ `kvcache_partition_len`.
289
+
290
+ The choice impacts performance and memory usage, especially for long sequences.
291
+ Constraints related to `max_seq_len` and `kvcache_partition_len` apply when using
292
+ `"flash_attn"`.
293
+
294
+
295
+ KV Cache Partition Length:
296
+ `kvcache_partition_len` is relevant **only** when `attn_impl` is `"flash_attn"`.
297
+
298
+ - It defines the length (number of tokens) of each partition within the Key-Value (KV) cache.
299
+ - Must be between 4,096 and 32,768 (inclusive).
300
+ - When using `"flash_attn"`, `max_seq_len` must be a multiple of `kvcache_partition_len`
301
+ and at least twice its value (`max_seq_len >= 2 * kvcache_partition_len`).
302
+ - If `attn_impl` is `"flash_attn"` and `kvcache_partition_len` is `None`, it defaults to
303
+ 16,384.
304
+
305
+
306
+ KV Cache Number of Blocks:
307
+ `kvcache_num_blocks` controls the total number of memory blocks allocated for the PagedAttention KV cache.
308
+ Each block holds `kvcache_block_size` tokens of Key and Value states.
309
+
310
+ - **Automatic Estimation (Default)**: If `kvcache_num_blocks` is `None`, the system estimates
311
+ the maximum number of blocks that can fit into the available RBLN device memory. This
312
+ calculation considers the model size (kernel memory), required buffer memory, the number
313
+ of layers and heads, `kvcache_block_size`, tensor parallelism, and available RBLN NPU DRAM.
314
+ This aims to maximize cache capacity for potentially better performance with long sequences
315
+ or larger batches without manual tuning.
316
+ - **Manual Setting**: You can explicitly set the number of blocks. This provides finer control
317
+ but requires careful consideration of memory limits. Setting it too high may lead to
318
+ compilation errors if it exceeds available memory. The system will issue warnings if your
319
+ setting exceeds the estimated maximum.
320
+ - **Performance Impact**: A larger number of blocks reduces the likelihood of cache eviction,
321
+ which is beneficial for tasks involving many long sequences or large batch sizes, enabling
322
+ higher throughput. However, allocating more blocks consumes more memory.
323
+ - **Minimum Requirement**: The system requires a minimum number of blocks to function,
324
+ calculated based on `max_seq_len`, `kvcache_block_size`, and `batch_size`. The number of
325
+ allocated blocks must be sufficient to hold at least one full sequence length per item
326
+ in the batch concurrently. The system will log warnings or raise errors if constraints
327
+ are violated (e.g., if `kvcache_num_blocks` is less than `batch_size` when using Flash Attention).
328
+
329
+ The optimal value depends on the specific model, task, hardware, and desired trade-off
330
+ between performance and memory usage. The automatic estimation provides a robust starting point.
331
+ """
332
+
333
+ super().__init__(
334
+ max_seq_len=max_seq_len,
335
+ use_inputs_embeds=use_inputs_embeds,
336
+ use_attention_mask=use_attention_mask,
337
+ use_position_ids=use_position_ids,
338
+ attn_impl=attn_impl,
339
+ kvcache_partition_len=kvcache_partition_len,
340
+ kvcache_block_size=kvcache_block_size,
341
+ quantization=quantization,
342
+ prefill_chunk_size=prefill_chunk_size,
343
+ kvcache_num_blocks=kvcache_num_blocks,
344
+ cache_impl=cache_impl,
345
+ sliding_window=sliding_window,
346
+ sliding_window_layers=sliding_window_layers,
347
+ **kwargs,
348
+ )
349
+
350
+ # override batch_size for causal lm
351
+ self.batch_size = batch_size or 1
352
+ if not isinstance(self.batch_size, int) or self.batch_size < 0:
353
+ raise ValueError(f"batch_size must be a positive integer, got {self.batch_size}")
354
+
355
+ if phases is not None:
356
+ self.validate_phases_type(phases)
357
+ self.phases = phases or ["prefill", "decode"]
358
+
359
+ if "decode" in self.phases:
360
+ self.decoder_batch_sizes = decoder_batch_sizes
361
+ if self.decoder_batch_sizes is None:
362
+ self.decoder_batch_sizes = [self.batch_size]
363
+
364
+ if self.use_multiple_decoder:
365
+ if max(self.decoder_batch_sizes) > self.batch_size:
366
+ raise ValueError(
367
+ f"Decoder batch size ({max(self.decoder_batch_sizes)}) must be less than or equal to the runtime batch size ({self.batch_size})."
368
+ )
369
+ if max(self.decoder_batch_sizes) < self.batch_size:
370
+ logger.warning(
371
+ f"Maximum decoder batch size ({max(self.decoder_batch_sizes)}) is less than the model's batch size ({self.batch_size}). "
372
+ "Appending the model's batch size to the decoder batch size."
373
+ )
374
+ self.decoder_batch_sizes.append(self.batch_size)
375
+
376
+ # Larger batch size should be at the beginning of the list.
377
+ self.decoder_batch_sizes.sort(reverse=True)
378
+
379
+ @staticmethod
380
+ def validate_phases_type(phases: List[PhaseType]):
381
+ if not isinstance(phases, list):
382
+ raise ValueError("`phases` must be a list.")
383
+ if not all(phase in get_args(PhaseType) for phase in phases):
384
+ raise ValueError(f"All elements in `phases` must be of type `PhaseType`({get_args(PhaseType)}).")
385
+
221
386
  @property
222
387
  def use_multiple_decoder(self):
223
388
  return isinstance(self.decoder_batch_sizes, list) and len(self.decoder_batch_sizes) > 1
389
+
390
+ @property
391
+ def can_generate(self):
392
+ return "decode" in self.phases