-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathdrive_paged_programs.py
More file actions
1526 lines (1340 loc) · 58.6 KB
/
drive_paged_programs.py
File metadata and controls
1526 lines (1340 loc) · 58.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
from dataclasses import dataclass
from datetime import datetime
import itertools
import json
import os
from pathlib import Path
import random
import time
from itertools import dropwhile
import re
from typing import Any, Dict, Iterable, List, Literal, NamedTuple, Optional, Tuple
import torch
from fms.models import get_model
from fms.utils.generation import pad_input_ids
from torch import distributed as dist
from torch.fx.experimental import _config as fx_config
from transformers import AutoTokenizer
from aiu_fms_testing_utils.utils.dpp_config import DPPRunnerConfig
from aiu_fms_testing_utils.utils.env_utils import scoped_environ
from aiu_fms_testing_utils.testing.validation import (
GoldenTokenHook,
LogitsExtractorHook,
ValidationInfo,
capture_level_1_metrics,
extract_validation_information,
filter_failed_level_1_cases,
find_validation_info_path,
get_validation_info_path,
load_validation_information,
top_k_loss_calculator,
)
from aiu_fms_testing_utils.utils import (
get_pad_size,
sample_rag_factoid_requests,
sample_sharegpt_requests,
stagger_region,
warmup_model
)
from aiu_fms_testing_utils.utils.aiu_setup import aiu_dist_setup, dprint, local_rank
from aiu_fms_testing_utils.utils.paged import (
ProgramCriteria,
get_programs_prompts,
)
from aiu_fms_testing_utils.testing.utils import format_kwargs_to_string
from aiu_fms_testing_utils.utils.resource_collection import (
instantiate_prometheus, print_step
)
# Constants
PAD_MULTIPLE = 64
@dataclass
class ProgramInfo:
"""Encapsulates program execution criteria.
Attributes:
program_id: Unique identifier for the program being tested.
batch_size_limit: Numeric threshold for batch size constraint.
batch_size_limit_type: Comparison operator for batch size (e.g., ">=", "<=", "==").
prompt_length_limit: Numeric threshold for prompt length constraint.
prompt_length_limit_type: Comparison operator for prompt length (e.g., ">=", "<=", "==").
"""
program_id: str
batch_size_limit: int
batch_size_limit_type: str
prompt_length_limit: int
prompt_length_limit_type: str
class EnvConfig(NamedTuple):
"""Represents global configuration derived from environment and CLI.
Attributes:
attn_name: The internal name of the attention algorithm (e.g., 'spyre_paged_attn').
cpu_dtype: Data type for CPU validation ('fp8' or 'fp32').
max_batch_size: Maximum batch size.
max_tkv: Maximum total key-value (context) length.
"""
attn_name: str
cpu_dtype: str
max_batch_size: int
max_tkv: int
class MetricResult(NamedTuple):
"""Result of comparing AIU and CPU logit distributions.
Attributes:
cross_entropy_loss: Cross-entropy loss between the distributions.
mean_abs_diff: Mean absolute difference of softmax probabilities.
"""
cross_entropy_loss: float
mean_abs_diff: float
def __str__(self) -> str:
return f"cross_entropy_loss: {self.cross_entropy_loss:.6f}, mean_abs_diff: {self.mean_abs_diff:.6f}"
class PreparedInputs(NamedTuple):
"""Represents prepared model inputs from dataset sampling.
Attributes:
input_ids: Padded tensor of tokenized input IDs with shape (batch_size, seq_length).
extra_kwargs: Dictionary with attention mask and other model inputs.
sample_key: String identifier for the sampled prompts.
"""
input_ids: torch.Tensor
extra_kwargs: Dict[str, Any]
sample_key: str
class ValidPrompt(NamedTuple):
"""Represents a valid prompt configuration for program execution.
Attributes:
program_id: ID of the program this prompt will execute.
shape: Tuple of (batch_size, seq_length) for this prompt.
input_ids: Tokenized and padded input tensor.
extra_kwargs: Dictionary with attention mask and other model inputs.
sample_key: String identifier for the sampled prompts.
"""
program_id: str
shape: Tuple[int, int]
input_ids: torch.Tensor
extra_kwargs: Dict[str, Any]
sample_key: str
def parse_cli_args() -> argparse.Namespace:
"""
Initializes the argument parser and parses command-line arguments.
Returns:
argparse.Namespace: An object containing the parsed arguments.
"""
parser = argparse.ArgumentParser(
description="Script which will drive paged programs for debugging"
)
parser.add_argument(
"--programs",
metavar="N",
type=str,
nargs="*",
default=[],
help="""
The list of programs to run. This would take a list where each element would be one of program_id OR <program_id>:<min_batch>,<min_prompt_length>.
If program_id is specified any prompt that would result in this program would be selected.
If <program_id>:<min_batch>,<min_prompt_length> is specified, then with the given program_id, select a prompt that satisfies min_batch and min_prompt_length (if none exists, a message will be printed to warn the user)
If this list is empty, each program will be run once with any prompt that would result in this program being selected.
""",
)
parser.add_argument(
"--max_new_tokens",
type=int,
default=8,
help="set this if you want to change the number of tokens generated per sequence (1 prefill + max_new_tokens-1 decodes). Note: If this value is larger than 64, this may result in switching decode programs mid generation",
)
parser.add_argument(
"--distributed",
action="store_true",
help="This is a distributed job (multiple instances run with RANK+WORLD_SIZE)",
)
parser.add_argument(
"--model_variant",
type=str,
default="ibm-ai-platform/micro-g3.3-8b-instruct-1b",
help="The model id or path to use for this test. Note: must be a huggingface format",
)
parser.add_argument(
"--timing",
type=str,
choices=["e2e", "per-token"],
default="",
help="if set, how to time the generation of tokens, e2e or per-token",
)
parser.add_argument(
"--program_criteria_json_path",
type=str,
help="path to json file containing the program criteria list",
)
parser.add_argument(
"--dataset_path",
type=str,
help="path to dataset",
)
parser.add_argument(
"--dataset_type",
type=str,
choices=["rag_factoid", "sharegpt", "custom"],
default="sharegpt",
help="selects the correct dataset type for sampling. Must be one of rag_factoid or sharegpt or custom",
)
parser.add_argument(
"--test_type",
type=str,
choices=["tokens", "metrics"],
default="metrics",
help="set the type of the test that you would like to run. If metrics, will inject tokens and get metrics. If tokens, will not inject tokens and get tokens",
)
parser.add_argument(
"--cross_entropy_threshold",
type=float,
default=2.5,
help="threshold to denote passing/failing a given iteration",
)
parser.add_argument(
"--failure_rate_threshold",
type=float,
default=0.1,
help="the threshold which denotes whether to pass or fail the test. The failure threshold is defined as the number of failing iterations (cross_entropy) over the total iterations. If this value exceeds the failure_rate_threshold, we will fail the test",
)
parser.add_argument(
"--attention_type",
type=str,
default="paged",
choices=["paged", "paged_fp8"],
help="The attention type to use",
)
parser.add_argument(
"--prefill_chunk_size",
type=int,
default=0,
help="if > 0, activate chunked prefill, with chunk_size=this_argument. Only works with paged attention variants.",
)
parser.add_argument(
"--stagger_load",
type=int,
default=0,
help="Limit the number of concurrent processes executing the model loading phase. Set to 0 to allow all processes",
)
parser.add_argument(
"--stagger_update_lazyhandle",
type=int,
default=0,
help="Limit the number of concurrent processes executing the AIU update_lazyhandle phase. Set to 0 to allow all processes",
)
parser.add_argument(
"--dist_timeout",
type=int,
default=0,
help="Timeout to use for messaging in minutes. Default set by PyTorch dist.init_process_group",
)
parser.add_argument(
"--skip_validation",
action="store_true",
help="set to true to skip cpu validation",
)
parser.add_argument(
"--validation_info_outputs_dir",
type=str,
default="/home/senuser/models/validation_info",
help="path to directory containing validation info outputs",
)
parser.add_argument(
"--save_validation_info_outputs",
action="store_true",
help="set to true to save cpu validation outputs for later consumption",
)
parser.add_argument(
"--prioritize_large_batch_sizes",
action="store_true",
help="set to true if you would like to prioritize large batch sizes",
)
parser.add_argument(
"--enforce_homogeneous_prompt_programs",
action="store_true",
help="set to true ensure that all prompts hit the same prompt program for a given test",
)
return parser.parse_args()
def _prepare_inputs(
batch_size: int,
seq_length: int,
tokenizer: AutoTokenizer,
sampler,
dataset_path: str,
allow_truncation: bool,
enforce_sizes: List[int] = [],
seed: int = 0,
) -> PreparedInputs:
"""Prepares and tokenizes input prompts for model inference.
Samples prompts from a dataset using the provided sampler, tokenizes them,
and pads them to the specified sequence length. Handles cases where fewer
prompts are available than requested by repeating the first prompt.
Args:
batch_size: Number of prompts to sample for the batch.
seq_length: Target sequence length for padding.
tokenizer: HuggingFace tokenizer for encoding prompts.
sampler: Callable that samples prompts from the dataset.
dataset_path: Path to the dataset file.
allow_truncation: If True, allows truncating prompts longer than seq_length.
enforce_sizes: List of specific sequence lengths to enforce for sampling.
seed: Random seed for reproducible sampling.
Returns:
Tuple containing:
- input_ids: Padded tensor of tokenized input IDs with shape (batch_size, seq_length).
- extra_kwargs: Dictionary with additional model inputs including attention mask.
- sample_key: String identifier for the sampled prompts.
Raises:
ValueError: If no valid prompts exist in the dataset for the requested shape.
"""
start = time.time()
prompts_and_sizes, sample_key = sampler(
dataset_path,
batch_size,
tokenizer,
32,
seq_length * 2 if allow_truncation else seq_length,
seed,
enforce_sizes=enforce_sizes,
truncation=allow_truncation,
return_key=True,
)
end = time.time()
if local_rank == 0:
dprint(f"extracted prompts in {(end - start):.4f} seconds")
prompt_list = []
for prompt, size in prompts_and_sizes:
encoded = tokenizer.encode(prompt, return_tensors="pt").squeeze(0)
if size > seq_length:
assert allow_truncation
encoded = encoded[:seq_length]
prompt_list.append(encoded)
if not prompt_list:
raise ValueError(
f"No valid prompt sample exists in dataset for input shape (Batch Size={batch_size}, Seq Length={seq_length})"
)
if len(prompt_list) < batch_size:
dprint(
f"You requested {batch_size} prompts but we were only able to get {len(prompt_list)} valid prompts. We will be repeating the first prompt."
)
prompt_list = [prompt_list[0]] * (batch_size - len(prompt_list)) + prompt_list
input_ids, extra_kwargs = pad_input_ids(prompt_list, min_pad_length=seq_length)
extra_kwargs["mask"] = extra_kwargs["mask"].to(torch.float16)
return PreparedInputs(
input_ids=input_ids, extra_kwargs=extra_kwargs, sample_key=sample_key
)
def _maybe_prepare_fp8_weights(model: torch.nn.Module, is_fp8: bool) -> None:
"""Converts model weights from bfloat16 to float16 for FP8 attention.
When using FP8 attention variants, this function converts all bfloat16 parameters
to float16. Issues a warning if any parameter values exceed the float16 range,
which may cause accuracy loss.
Args:
model: PyTorch model whose weights may need conversion.
is_fp8: If True, performs the weight conversion.
"""
if is_fp8:
for name, param in model.named_parameters():
if param.dtype == torch.bfloat16:
if param.max() > torch.finfo(torch.float16).max:
dprint(
f"[WARNING] You are casting param {name} to fp16, which will cause loss of accuracy. You can ignore this warning if this is intended."
)
param.data = param.data.to(dtype=torch.float16)
def _load_validation_info(
model_variant,
batch_size,
seq_length,
max_new_tokens,
tokenizer,
seed,
cpu_dtype: str,
attn_type: str,
validation_info_outputs_dir: str,
sample_key: str | None = None,
) -> ValidationInfo | None:
"""Loads pre-computed CPU validation information from disk if available.
Searches for a previously saved validation info file matching the specified
parameters. If found, loads and returns the validation information to avoid
redundant CPU computation.
Args:
model_variant: Model identifier or path (HuggingFace format).
batch_size: Batch size used for validation.
seq_length: Sequence length used for validation.
max_new_tokens: Number of tokens to generate during validation.
tokenizer: HuggingFace tokenizer for the model.
seed: Random seed used for validation.
cpu_dtype: Data type string for CPU validation ("fp8" or "fp32").
attn_type: Attention algorithm type used.
validation_info_outputs_dir: Directory containing saved validation outputs.
sample_key: Optional identifier for the specific prompt sample used.
Returns:
ValidationInfo object if a matching file is found, None otherwise.
"""
full_path = find_validation_info_path(
validation_info_dir=validation_info_outputs_dir,
model_variant=model_variant,
batch_size=batch_size,
seq_length=seq_length,
max_new_tokens=max_new_tokens,
seed=seed,
attn_type=attn_type,
version_allow_decrement=True,
dtype=cpu_dtype,
sample_key=sample_key,
)
if full_path is not None:
dprint(f"cpu validation info found for seed={seed} -- loading it")
return load_validation_information(full_path, "logits", batch_size, tokenizer)
else:
return None
def parse_program_limit(limit_str: str) -> tuple[int, str | None]:
"""Parses a program limit string into a numeric value and comparison operator.
Accepts either a plain integer (defaults to ">=" for backward compatibility)
or a string with a comparison operator prefix (e.g., ">=10", "<5", "==8").
Args:
limit_str: String representation of the limit, either a number or
operator+number (e.g., "10", ">=10", "<5").
Returns:
Tuple containing:
- limit_val: The numeric limit value.
- limit_type: The comparison operator string (">=", "<=", "<", ">", "==").
Raises:
ValueError: If the limit string format is invalid.
"""
matcher = re.compile(r"^(<|>|<=|>=|==)(\d+)")
# Default limit to min to maintain backwards compat
try:
limit_type = ">="
limit_val = int(limit_str)
except ValueError:
limit_type = None
match = matcher.fullmatch(limit_str)
if match is None:
raise ValueError("Program not well formatted, wrong limit type")
limit_type = match.group(1)
limit_val = int(match.group(2))
return limit_val, limit_type
def _metric_calculator(r: torch.Tensor, t: torch.Tensor):
"""Calculates cross-entropy and mean absolute difference between logit distributions.
Args:
r: Reference logits tensor from CPU validation.
t: Test logits tensor from AIU inference.
Returns:
MetricResult: A named tuple containing the calculated metrics.
"""
cross_entropy_loss = torch.nn.CrossEntropyLoss()(
r, t.softmax(dim=1).to(dtype=torch.float32)
)
mean_abs_diff = torch.mean(
torch.abs(
r.softmax(dim=1).to(dtype=torch.float32)
- t.softmax(dim=1).to(dtype=torch.float32)
)
)
return MetricResult(
cross_entropy_loss=cross_entropy_loss.item(), mean_abs_diff=mean_abs_diff.item()
)
def _get_model_kwargs(model_variant: str) -> Dict[str, Any]:
"""Constructs model loading kwargs based on whether variant is a path or ID.
Determines if the model_variant is a local filesystem path or a HuggingFace
model identifier, and returns the appropriate keyword arguments for model loading.
Args:
model_variant: Either a local path to model files or a HuggingFace model ID.
Returns:
Dictionary with either "model_path" (for local paths) or "variant"
(for HuggingFace IDs) as the key.
"""
model_kwargs = {}
if os.path.exists(model_variant):
model_kwargs["model_path"] = model_variant
else:
model_kwargs["variant"] = model_variant
return model_kwargs
def _get_distributed_kwargs(
is_distributed: bool,
dist_timeout: str,
) -> Dict[str, Any]:
"""Initializes distributed training configuration and returns kwargs.
Sets up PyTorch distributed process group with tensor parallelism strategy
if distributed mode is enabled. Configures custom timeout if specified.
Args:
is_distributed: If True, initializes distributed training setup.
dist_timeout: Timeout in minutes for distributed operations (0 uses default).
Returns:
Dictionary containing distributed configuration with keys:
- "distributed_strategy": Set to "tp" (tensor parallelism) if distributed.
- "group": PyTorch distributed group (WORLD) if distributed.
Returns empty dict if not distributed.
"""
distributed_kwargs = {}
if is_distributed:
if dist_timeout > 0:
# Default timeout:
# https://docs.pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group
dist.init_process_group(timeout=datetime.timedelta(minutes=dist_timeout))
dprint(f"NOTICE: init_process_group timeout set to {dist_timeout} minutes")
else:
dist.init_process_group()
aiu_dist_setup(dist.get_rank(), dist.get_world_size())
distributed_kwargs["distributed_strategy"] = "tp"
distributed_kwargs["group"] = dist.group.WORLD
return distributed_kwargs
def get_sampler(dataset_type: str, dataset_path: str, tokenizer: AutoTokenizer):
"""Selects and configures the sampler based on type.
Returns a sampler function and configuration for the specified dataset type.
Args:
dataset_type: Type of dataset ("custom", "rag_factoid", or "sharegpt").
dataset_path: Path to the dataset file or directory.
tokenizer: HuggingFace tokenizer for encoding prompts.
Returns:
Tuple containing:
- sampler: Callable function for sampling prompts from the dataset.
- allow_truncation: Boolean indicating if prompt truncation is allowed.
- custom_shape: Tuple of (batch_size, max_seq_length) for custom datasets,
None for other dataset types.
Raises:
ValueError: If dataset_type is not one of the supported types.
SystemExit: If custom dataset path is not a directory or file reading fails.
"""
custom_shape = None
if dataset_type == "custom":
if local_rank == 0:
dprint(
"Using custom prompts from user, programs parameter will be ignored as it will be determined by user prompt"
)
directory = Path(dataset_path)
if not directory.is_dir():
dprint("when using a custom dataset, you must provide a directory")
exit()
result = []
for fp in directory.iterdir():
if fp.is_file():
try:
content = fp.read_text()
result.append(
(content, get_pad_size(len(tokenizer.encode(content))))
)
except Exception as e:
print(f"Error while reading {fp} for custom dataset: {e}")
exit()
custom_shape = (len(result), max([_[1] for _ in result]))
def _custom_line_sampler(**kwargs):
"""Custom sampler for user-provided text files.
Returns pre-loaded prompts from custom dataset files without
additional sampling logic. Supports optional sample key return.
Args:
**kwargs: Keyword arguments, supports "return_key" flag.
Returns:
List of (prompt, padded_size) tuples, or tuple of (list, sample_key)
if return_key=True.
"""
return_key = kwargs.get("return_key", False)
sample_key = format_kwargs_to_string(**kwargs)
if return_key:
return result, sample_key
return result
sampler = _custom_line_sampler
allow_truncation = False
elif dataset_type == "rag_factoid":
sampler = sample_rag_factoid_requests
allow_truncation = False
elif dataset_type == "sharegpt":
sampler = sample_sharegpt_requests
allow_truncation = True
else:
raise ValueError("dataset_type must be one of rag_factoid or sharegpt")
return sampler, allow_truncation, custom_shape
def load_model(
device_type: Literal["cpu", "spyre"],
is_fp8: bool,
model_kwargs: Dict[str, Any],
distributed_kwargs: Dict[str, Any],
stagger_load: int,
model_config: DPPRunnerConfig,
):
"""Loads and optionally compiles a model for inference or validation.
Loads a model with the specified configuration. For Spyre/AIU models,
compiles the model using the sendnn backend with dynamic compilation enabled.
The scoped_environ context manager temporarily sets environment variables
from model_config during compilation to configure the compiler's behavior (e.g.,
program criteria, batch sizes, context lengths).
Args:
device_type: Target device for model execution. Options:
- "cpu": Load on CPU for validation (fp32, no compilation)
- "spyre": Load on CPU, compile for Spyre/AIU execution (fp16, with sendnn compilation)
is_fp8: If True, uses FP8 quantization (dtype=None for auto-detection).
model_kwargs: Dictionary with model loading parameters (variant or path).
distributed_kwargs: Dictionary with distributed training configuration.
stagger_load: Number of concurrent processes allowed during loading (0=unlimited).
model_config: DPPRunnerConfig instance with environment variable updates.
Returns:
torch.nn.Module: Loaded model in evaluation mode. Spyre models are compiled
with sendnn backend and may have FP8 weight conversion applied.
"""
if device_type not in ["cpu", "spyre"]:
raise ValueError(
f"device_type must be 'cpu' or 'spyre' for DPP, got '{device_type}'"
)
dtype = (
(torch.float32 if device_type == "cpu" else torch.float16)
if not is_fp8
else None
)
with stagger_region(stagger_load):
model = get_model(
architecture="hf_pretrained",
device_type="cpu",
data_type=dtype,
fused_weights=False,
**model_kwargs,
**distributed_kwargs,
)
model.eval()
if device_type == "spyre":
with scoped_environ(model_config.env_updates()):
# Temporarily set environment variables needed for compile
model.compile(backend="sendnn", options={"sendnn.dynamic": True})
_maybe_prepare_fp8_weights(model, is_fp8)
return model
def get_programs_to_test(programs, program_criteria_list) -> list[ProgramInfo]:
"""Parses program specifications into ProgramInfo objects for testing.
Converts command-line program specifications into structured ProgramInfo objects.
Supports three formats:
- Empty list: Tests all programs with any valid prompt.
- "program_id": Tests specific program with any valid prompt.
- "program_id:batch_constraint,prompt_constraint": Tests program with specific constraints.
Args:
programs: List of program specification strings from command line.
program_criteria_list: List of ProgramCriteria objects defining available programs.
Returns:
List of ProgramInfo objects representing programs to test with their constraints.
"""
programs_to_test = []
for program_str in programs:
enforce_prompt_split = program_str.split(":")
program_id = enforce_prompt_split[0]
if len(enforce_prompt_split) == 1:
programs_to_test.append(
ProgramInfo(program_id, 0, ">=", 0, ">=")
) # this will always satisfy
else:
enforce_batch_size, enforce_prompt_length = (
_ for _ in enforce_prompt_split[1].split(",")
)
# Default limit to min to maintain backwards compat
enforce_batch_size_val, enforce_batch_size_type = parse_program_limit(
enforce_batch_size
)
enforce_prompt_length_val, enforce_prompt_length_type = parse_program_limit(
enforce_prompt_length
)
programs_to_test.append(
ProgramInfo(
program_id,
enforce_batch_size_val,
enforce_batch_size_type,
enforce_prompt_length_val,
enforce_prompt_length_type,
)
)
if len(programs_to_test) == 0:
programs_to_test = [
ProgramInfo(str(p.program_id), 0, ">=", 0, ">=")
for p in program_criteria_list
]
return programs_to_test
def get_valid_prompts(
program_map,
dataset_path: str,
enforce_homogeneous_prompt_programs: bool,
programs_to_test: List[ProgramInfo],
program_criteria_list: List[ProgramCriteria],
tokenizer: AutoTokenizer,
sampler,
allow_truncation: bool,
custom_shape: Optional[Tuple[int, int]],
pad_multiple: int,
):
"""Generator that yields valid prompts matching program criteria and constraints.
Iterates through programs to test and finds prompts from the dataset that satisfy
the program's batch size and prompt length constraints. For custom datasets, uses
the provided shape directly. For other datasets, samples prompts matching the
program criteria. When enforce_homogeneous_prompt_programs is True, generates
multiple sequence lengths within a batch to ensure all prompts hit the same program.
Args:
program_map: Dictionary mapping program sequences to valid prompt shapes.
dataset_path: Path to the dataset for sampling prompts.
enforce_homogeneous_prompt_programs: If True, ensures all prompts in a batch
use the same decode program.
programs_to_test: List of ProgramInfo objects specifying programs and constraints.
program_criteria_list: List of ProgramCriteria defining program boundaries.
tokenizer: HuggingFace tokenizer for encoding prompts.
sampler: Callable for sampling prompts from the dataset.
allow_truncation: If True, allows truncating prompts exceeding max length.
custom_shape: Optional tuple of (batch_size, seq_length) for custom datasets.
pad_multiple: Padding granularity for sequence lengths (typically 64).
Yields:
ValidPrompt: A named tuple containing program_id, shape, input_ids,
extra_kwargs, and sample_key.
"""
# select prompts that fit the batch size criteria
if custom_shape:
prompt_found = 0
for program_criteria_seq, valid_prompt_shapes in program_map.items():
for valid_prompt_shape in valid_prompt_shapes:
if valid_prompt_shape == custom_shape:
enforce_sizes = [valid_prompt_shape[1]]
input_ids, extra_kwargs, sample_key = _prepare_inputs(
batch_size=valid_prompt_shape[0],
seq_length=valid_prompt_shape[1],
tokenizer=tokenizer,
sampler=sampler,
dataset_path=dataset_path,
allow_truncation=allow_truncation,
enforce_sizes=enforce_sizes,
)
prompt_found = 1
yield ValidPrompt(
program_id=program_criteria_seq[0].program_id,
shape=custom_shape,
input_ids=input_ids,
extra_kwargs=extra_kwargs,
sample_key=sample_key,
)
break
if prompt_found:
break
else:
for program_info in programs_to_test:
program_id = program_info.program_id
filtered_program_map = program_map
if program_id.isnumeric():
filtered_program_map = {
k: v
for k, v in program_map.items()
if k[0] == program_criteria_list[int(program_id)]
}
used_keys = set()
# for each program, we need to check if we have a shape that satisfies the --programs request
for program_seq_key, valid_prompt_shapes in filtered_program_map.items():
# if ? or numeric => we need to check if we have found at least one valid key to stop
if (program_id == "?" or program_id.isnumeric()) and len(used_keys) > 0:
break
# if * => we need to see if we have found the first key to see if we should skip
elif program_id == "*" and program_seq_key[0] in used_keys:
continue
for valid_prompt_shape in valid_prompt_shapes:
# make sure the criteria for batch limit and prompt limit is satisfied
# eval is safe here because we have limited what type and limit can be before
batch_check = eval(
f"valid_prompt_shape[0] {program_info.batch_size_limit_type} {program_info.batch_size_limit}"
)
prompt_check = eval(
f"valid_prompt_shape[1] {program_info.prompt_length_limit_type} {program_info.prompt_length_limit}"
)
if batch_check and prompt_check:
# when we enforce homogeneous prompt programs, we will cycle through all sizes between the min of a program and the valid prompt sequence length
# if there does not exist enough sequence sizes between this range, we will cycle back to the beginning
# in the event we don't have enough sequences that satisfy the enforce_sizes, we will repeat sequences and warn the user
enforce_sizes = [valid_prompt_shape[1]]
if enforce_homogeneous_prompt_programs:
# this will get the number of bits for the sequence length and shift to get the power of 2 that is less than or equal to the sequence length
tkv_cutoff = 1 << (valid_prompt_shape[1].bit_length() - 1)
possible_seq_lengths = [
_
for _ in range(
tkv_cutoff, valid_prompt_shape[1], pad_multiple
)
]
# favor sequences that are close to the valid prompt length
possible_seq_lengths.reverse()
enforce_sizes = enforce_sizes + list(
itertools.islice(
itertools.cycle(possible_seq_lengths),
valid_prompt_shape[0] - 1,
)
)
try:
input_ids, extra_kwargs, sample_key = _prepare_inputs(
batch_size=valid_prompt_shape[0],
seq_length=valid_prompt_shape[1],
tokenizer=tokenizer,
sampler=sampler,
dataset_path=dataset_path,
allow_truncation=allow_truncation,
enforce_sizes=enforce_sizes,
)
used_keys.add(program_seq_key[0])
yield ValidPrompt(
program_id=program_seq_key[0],
shape=valid_prompt_shape,
input_ids=input_ids,
extra_kwargs=extra_kwargs,
sample_key=sample_key,
)
break
except ValueError:
dprint(
f"No valid sample exists in dataset for this input shape {valid_prompt_shape}"
)
if len(used_keys) == 0 and local_rank == 0:
dprint(
f"no valid prompt shape was found which would result in program {program_id} that satisfied batch{program_info.batch_size_limit_type}{program_info.batch_size_limit} and prompt_length{program_info.prompt_length_limit_type}{program_info.prompt_length_limit}"
)
def generate_cpu_validation(
model_variant: str,
max_new_tokens: int,
validation_info_outputs_dir: str,
save_validation_info_outputs: bool,
validation_model: torch.nn.Module,
valid_prompt,
input_ids: torch.Tensor,
extra_kwargs: Dict[str, Any],
sample_key: str,
attn_name: str,
cpu_dtype: str,
tokenizer: AutoTokenizer,
) -> ValidationInfo:
"""Generates or loads CPU validation information for reference comparison.
Attempts to load pre-computed CPU validation data from disk. If not found,
runs CPU inference to generate reference outputs (tokens and logits).
Optionally saves the validation info for future use.
Args:
model_variant: Model identifier or path.
max_new_tokens: Maximum number of tokens to generate.
validation_info_outputs_dir: Directory for validation info outputs.
save_validation_info_outputs: Whether to save validation info to disk.
validation_model: CPU model for generating validation data.
valid_prompt: Tuple of (batch_size, seq_length) for the prompt shape.
input_ids: Tokenized input tensor.
extra_kwargs: Dictionary with attention mask and other model inputs.
sample_key: String identifier for the sampled prompts.
attn_name: Name of the attention algorithm used.
cpu_dtype: Data type string for CPU validation ("fp8" or "fp32").
tokenizer: HuggingFace tokenizer for the model.
Returns:
ValidationInfo: ValidationInfo object containing CPU reference outputs
(tokens and logits).
"""
# attempt to load the cpu validation info if it is already computed
cpu_validation_info = _load_validation_info(
model_variant=model_variant,
batch_size=valid_prompt[0],
seq_length=valid_prompt[1],
max_new_tokens=max_new_tokens,
tokenizer=tokenizer,
seed=0,
cpu_dtype=cpu_dtype,
attn_type=attn_name,
validation_info_outputs_dir=validation_info_outputs_dir,
sample_key=sample_key,
)
if cpu_validation_info is None:
cpu_validation_info = extract_validation_information(
model=validation_model,
input_ids=input_ids,
max_new_tokens=max_new_tokens,
post_iteration_hook=LogitsExtractorHook(),
attn_algorithm="math",
**extra_kwargs,
)
if save_validation_info_outputs:
cpu_validation_info.save(
get_validation_info_path(
validation_info_dir=validation_info_outputs_dir,
model_variant=model_variant,
batch_size=valid_prompt[0],
seq_length=valid_prompt[1],
max_new_tokens=max_new_tokens,
seed=0,
attn_type=attn_name,
dtype=cpu_dtype,
sample_key=sample_key,
)
)
return cpu_validation_info
def generate_aiu_validation(
test_type: str,
max_new_tokens: int,
timing: str,
prefill_chunk_size: int,
model: torch.nn.Module,
input_ids: torch.Tensor,
cpu_validation_info: Optional[ValidationInfo],
extra_kwargs: Dict[str, Any],
) -> ValidationInfo:
"""Generates AIU validation information by running inference on the compiled model.
Executes the AIU-compiled model to generate tokens and extract logits. If CPU
validation info is available and test_type is "metrics", injects golden tokens
from CPU validation to ensure consistent decode paths for metric comparison.
Args:
test_type: Type of test being run ("metrics" or "tokens").
max_new_tokens: Maximum number of tokens to generate.
timing: Whether to collect timing information.
prefill_chunk_size: Chunk size for prefill operations.
model: Compiled AIU model for inference.
input_ids: Tokenized input tensor.
cpu_validation_info: Optional CPU validation data for golden token injection.
extra_kwargs: Dictionary with attention mask and other model inputs.
Returns: