-
Notifications
You must be signed in to change notification settings - Fork 436
Expand file tree
/
Copy pathconftest.py
More file actions
1219 lines (979 loc) · 45.3 KB
/
conftest.py
File metadata and controls
1219 lines (979 loc) · 45.3 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
# SPDX-FileCopyrightText: © 2023 Tenstorrent USA, Inc.
# SPDX-License-Identifier: Apache-2.0
import contextlib
import json
import os
import random
import subprocess
from datetime import datetime
from functools import partial
from operator import contains, eq, getitem
from pathlib import Path
import numpy as np
import pytest
import torch
from loguru import logger
from models.tt_transformers.demo.trace_region_config import get_supported_trace_region_size
from tests.scripts.common import get_updated_device_params, run_process_and_get_result
# Constants for device configurations
SIX_U_NUM_PCIE_DEVICES = 32
@pytest.fixture(scope="function")
def reset_seeds():
torch.manual_seed(213919)
np.random.seed(213919)
random.seed(213919)
yield
@pytest.fixture(scope="function")
def function_level_defaults(reset_seeds):
yield
@pytest.fixture(scope="function")
def is_ci_env():
if os.getenv("CI") == "true":
return True
return False
@pytest.fixture(scope="function")
def is_single_card_n300(device):
import ttnn
num_pcie = ttnn.GetNumPCIeDevices()
return num_pcie == 1 and ttnn.cluster.get_cluster_type() == ttnn.cluster.ClusterType.N300
@pytest.fixture(scope="function")
def galaxy_type():
if is_6u():
return "6U"
elif is_tg_cluster():
return "4U"
else:
return None
def is_galaxy():
import ttnn
return ttnn.cluster.get_cluster_type() in [
ttnn.cluster.ClusterType.GALAXY,
ttnn.cluster.ClusterType.TG,
ttnn.cluster.ClusterType.BLACKHOLE_GALAXY,
]
# TODO: Remove this when TG clusters are deprecated.
def is_6u():
import ttnn
return ttnn.cluster.get_cluster_type() == ttnn.cluster.ClusterType.GALAXY
# TODO: Remove this when TG clusters are deprecated.
def is_tg_cluster():
import ttnn
return ttnn.cluster.get_cluster_type() == ttnn.cluster.ClusterType.TG
def first_available_tg_device():
assert is_tg_cluster()
# The id of the first user exposed device for a TG cluster is 4
return 4
@pytest.fixture(scope="session")
def is_ci_v2_env():
yield "TT_GH_CI_INFRA" in os.environ
# We don't want other people using this stuff... wonder if we should just stuff it in the fixture that's calling it instead
class CIv2ModelDownloadUtils_:
@staticmethod
def download_from_ci_v2_cache(
model_path,
timeout_in_s,
download_dir_suffix="",
endpoint_prefix="http://large-file-cache.large-file-cache.svc.cluster.local//mldata/model_checkpoints/pytorch/huggingface",
):
assert model_path, f"model_path cannot be empty when downloading - what is wrong with you?: {model_path}"
assert isinstance(
timeout_in_s, int
), f"{timeout_in_s} is not an integer, which it should be because it's a timeout duration"
# RK: Will this be portable? LOL
download_dir = Path("/tmp/ttnn_model_cache/") / download_dir_suffix
download_dir.mkdir(parents=True, exist_ok=True)
download_dir_str = str(download_dir)
# Add trailing slash to model_path if it doesn't have one, as wget
# seems to not download recursively via subprocess if it doesn't have
# it
if model_path and not model_path.endswith("/"):
model_path = model_path + "/"
endpoint = f"{endpoint_prefix}/{model_path}"
try:
# TODO: How do we add a timeout here without relying on native timeout command?
subprocess.run(
[
"wget",
"-r",
"-nH",
"-x",
"--cut-dirs=5",
"-np",
"--progress=dot:giga",
"-R",
"index.html*",
"-P",
download_dir_str,
endpoint,
],
check=True,
text=True,
timeout=timeout_in_s,
)
except subprocess.TimeoutExpired as err:
logger.error(f"Timeout of {timeout_in_s} seconds occurred while downloading from {endpoint}.")
raise err
except Exception as err:
logger.error(
f"Unknown error occurred while trying to download from {endpoint}. Check above logs from wget call."
)
logger.error(err)
raise err
return download_dir / Path(model_path)
@pytest.fixture(scope="session")
def model_location_generator(is_ci_v2_env):
"""
Returns a function that will determine the appropriate file path for a
model based on available locations.
This function locates model files by checking several possible locations in the following order:
1. CIv2 cache if running in CI environment and the user requests CIv2
resources via setting download_if_ci_v2 to True.
If we're in a CIv2 environment and download_if_ci_v2 is True, that means
the model is requesting files from CIv2. However, we will error out if
the files are not available because that means the responsible developer
did not properly uploaded the requested files.
2. Cloud MLPerf path if available, which is virtually all cases for CIv1
3. Default to the model_version string, which means downloading to the
local Huggingface cache directory (HF_HOME, or ~/.cache/huggingface by
default)
For CIv2 specifically
---------------------
The expected directory structure in the single source of truth datastore
should be:
lfc://mldata/model_checkpoints/pytorch/huggingface/pytorch
├── huggingface
└── hf_repo_owner/hf_repo
├── weight1.bin
├── weight2.bin
├── ...
└── T3K
├── T3K_ttnn_tensor1.bin
├── T3K_ttnn_tensor2.bin
└── ...
└── N300
├── N300_ttnn_tensor1.bin
├── N300_ttnn_tensor2.bin
└── ...
Why couple the TT-NN tensor binaries into the Huggingface model's folder?
This is because tensors are generated on a per-model basis, so in terms
of folder organization there isn't too much benefit from having a separate
place for HF weights and a separate place for the bins.
What's nice about this is this makes it clear which HF model corresponds
to which set of tensor binaries, which is useful for engineers to quickly
see which model is generating which binaries.
Note that the logic for all of this is in CIv2ModelDownloadUtils_.
:param model_version: The version identifier of the model to locate
:type model_version: str
:param model_subdir: Subdirectory within the model folder structure.
Default is empty string.
Note: Nested subdirectories (model_subdir) are not
supported in CIv2 cache.
:type model_subdir: str
:param download_if_ci_v2: Whether to download from CI v2 cache if in a CI v2 environment
:type download_if_ci_v2: bool
:param ci_v2_timeout_in_s: Timeout for download from CI v2 cache in seconds
:type ci_v2_timeout_in_s: int
:return: The path to the model files (internal MLPerf path, CI v2 cache
path, or just model_version which uses HF_HOME)
:rtype: os.PathLike (str, pathlib.Path etc.)
:raises AssertionError: If trying to run in CIv2 environment with MLPerf
files which is impossible, or if model_subdir contains unsupported
directory structure
"""
def model_location_generator_(
model_version,
model_subdir="",
download_if_ci_v2=False,
ci_v2_timeout_in_s=300,
endpoint_prefix="http://large-file-cache.large-file-cache.svc.cluster.local//mldata/model_checkpoints/pytorch/huggingface",
download_dir_suffix="model_weights",
):
model_folder = Path("tt_dnn-models") / model_subdir
internal_weka_path = Path("/mnt/MLPerf") / model_folder / model_version
has_internal_weka = internal_weka_path.exists()
download_from_ci_v2 = download_if_ci_v2 and is_ci_v2_env
if download_from_ci_v2:
assert (
not has_internal_weka
), "For some reason, we see a file existing at the expected MLPerf location: {internal_weka_path} on CIv2. Please use the opportunity to clean up your model and get rid of MLPerf if you're moving to CIv2"
assert (
not model_subdir
), f"model_subdir is set to {model_subdir}, but we don't support further levels of directories in the large file cache in CIv2"
civ2_download_path = CIv2ModelDownloadUtils_.download_from_ci_v2_cache(
model_version,
download_dir_suffix=download_dir_suffix,
timeout_in_s=ci_v2_timeout_in_s,
endpoint_prefix=endpoint_prefix,
)
logger.info(f"For model location, using CIv2 large file cache: {civ2_download_path}")
return civ2_download_path
elif has_internal_weka:
logger.info(f"For model location, using internal MLPerf path: {internal_weka_path}")
return internal_weka_path
else:
logger.info(
f"For model location, local copy not found, so likely downloading straight from HF: {model_version}"
)
return model_version
return model_location_generator_
@pytest.fixture(scope="session")
def get_tt_cache_path():
def get_tt_cache_path_(model_version, model_subdir="", default_dir=""):
model_folder = Path("tt_dnn-models/tt") / model_subdir
internal_weka_path = Path("/mnt/MLPerf") / model_folder / model_version
has_internal_weka = internal_weka_path.exists()
if has_internal_weka:
logger.debug(f"Using internal MLPerf path: {internal_weka_path}")
return internal_weka_path
else:
default_path = Path(default_dir) / model_folder / model_version
default_path.mkdir(parents=True, exist_ok=True)
logger.debug(f"Using default cache path: {default_path}")
return default_path
return get_tt_cache_path_
@pytest.fixture(scope="function")
def device_params(request):
return getattr(request, "param", {})
@pytest.fixture(scope="module")
def _device_module_impl(request):
"""
Internal module-scoped device fixture.
Do not request this fixture directly in test function signatures. Instead, use the
`device` fixture with @pytest.mark.use_module_device marker. When the marker is
present, the `device` fixture automatically delegates to this fixture via
request.getfixturevalue(), providing a module-scoped device while keeping test
signatures unchanged.
This optimization is intended for test modules where all tests share the same
device configuration. The device is created once per module and reused across
all tests, reducing setup/teardown overhead.
Usage in test files:
# Module scope, no special params:
pytestmark = pytest.mark.use_module_device
# Module scope WITH a single device configuration:
pytestmark = pytest.mark.use_module_device({"l1_small_size": 16384})
def test_something(device): # Just use 'device' as normal
...
IMPORTANT: Do NOT use this marker in test files that use parametrized device_params:
@pytest.mark.parametrize("device_params", [...], indirect=True)
Tests with multiple device configurations via parametrized device_params require
a fresh device for each parameter set and should continue using the default
function-scoped `device` fixture.
STATE SHARING CONSIDERATIONS:
Since the device is shared across all tests in a module, tests can affect each
other through accumulated device state:
- Program cache: Cached programs from earlier tests may be reused by later tests.
If tests require different program configurations (e.g., broadcast vs non-broadcast),
this can cause incorrect results. Call device.disable_and_clear_program_cache()
at the start of tests that are sensitive to cache state.
- Memory allocations: Tensors allocated on device persist until explicitly
deallocated or garbage collected. For highly parameterized tests, this can
exhaust device resources (TLBs, L1 memory). Tests should avoid holding
references to device tensors beyond what's needed.
- Device configuration: Any device configuration changes persist across tests.
WHEN TO USE MODULE SCOPE:
Module-scoped devices work best for:
- Tests that are stateless or don't depend on program cache state
- Tests that properly clean up device state when needed
- Test modules with many parameterized test cases (biggest time savings)
Avoid module scope for:
- Tests that assert on program cache entry counts
- Tests that require specific device initialization state
- Tests that use mesh_device or other multi-device fixtures
FAILURE HANDLING:
If a test fails or crashes, subsequent tests in the module will still run with
the same device. The device generally remains usable, but may have stale state.
For test isolation after failures, prefer function-scoped devices.
"""
import ttnn
device_id = request.config.getoption("device_id")
# Get device_params from marker - supports both patterns:
# @pytest.mark.use_module_device({"param": value}) # positional
# @pytest.mark.use_module_device(device_params={"param": value}) # keyword
marker = request.node.get_closest_marker("use_module_device")
if marker and marker.args:
device_params = marker.args[0]
elif marker and marker.kwargs:
# Validate kwargs - only 'device_params' is allowed
unexpected_kwargs = set(marker.kwargs.keys()) - {"device_params"}
if unexpected_kwargs:
raise ValueError(
f"@pytest.mark.use_module_device received unexpected keyword argument(s): "
f"{unexpected_kwargs}. Only 'device_params' is supported. "
f"Usage: @pytest.mark.use_module_device({{'l1_small_size': 16384}}) or "
f"@pytest.mark.use_module_device(device_params={{'l1_small_size': 16384}})"
)
device_params = marker.kwargs.get("device_params", {})
else:
device_params = {}
# When initializing a single device on a TG system, we want to
# target the first user exposed device, not device 0 (one of the
# 4 gateway devices)
if is_tg_cluster() and not device_id:
device_id = first_available_tg_device()
# Preserve original default device to restore on teardown
original_default_device = ttnn.GetDefaultDevice()
updated_device_params = get_updated_device_params(device_params)
device = ttnn.CreateDevice(device_id=device_id, **updated_device_params)
request.node.pci_ids = [ttnn.GetPCIeDeviceID(device_id)]
ttnn.SetDefaultDevice(device)
yield device
# Restore the original default device BEFORE closing the test-specific one
ttnn.SetDefaultDevice(original_default_device)
ttnn.close_device(device)
@pytest.fixture(scope="function")
def device(request, device_params):
"""
Primary device fixture - delegates to module-scoped or function-scoped implementation.
The device_params parameter is required even for the module-scoped path to detect
conflicting usage with @pytest.mark.parametrize("device_params", ...).
"""
import ttnn
# Check if file/test wants module-scoped device
if request.node.get_closest_marker("use_module_device"):
# device_params will be non-empty if test uses parametrized device_params,
# which conflicts with module-scoped device (can't vary device config per test)
if device_params:
raise ValueError(
"Cannot use @pytest.mark.use_module_device with "
"@pytest.mark.parametrize('device_params', ...). "
"Module-scoped devices are created once per module and cannot "
"vary per test. Either remove the marker to use function-scoped "
"device, or split tests with different device_params into separate files."
)
yield request.getfixturevalue("_device_module_impl")
return
device_id = request.config.getoption("device_id")
request.node.pci_ids = [ttnn.GetPCIeDeviceID(device_id)]
# When initializing a single device on a TG system, we want to
# target the first user exposed device, not device 0 (one of the
# 4 gateway devices)
if is_tg_cluster() and not device_id:
device_id = first_available_tg_device()
original_default_device = ttnn.GetDefaultDevice()
updated_device_params = get_updated_device_params(device_params)
device = ttnn.CreateDevice(device_id=device_id, **updated_device_params)
ttnn.SetDefaultDevice(device)
from tests.tests_common.cache_entries_counter import CacheEntriesCounter
device.cache_entries_counter = CacheEntriesCounter(device)
yield device
# Restore the original default device BEFORE closing the test-specific one
ttnn.SetDefaultDevice(original_default_device)
ttnn.close_device(device)
# Reset fabric config to DISABLED if not None, and do nothing otherwise
# Temporarily require previous state to be passed in as even setting it to DISABLED might be unstable
# This is to ensure that we don't propagate the instability to the rest of CI
def reset_fabric(fabric_config):
import ttnn
if fabric_config:
ttnn.set_fabric_config(ttnn.FabricConfig.DISABLED)
# Set fabric config to passed in value
# Do nothing if not set
# Must be called before creating the mesh device
def set_fabric(
fabric_config, reliability_mode=None, fabric_tensix_config=None, fabric_manager=None, fabric_router_config=None
):
import ttnn
# If fabric_config is not None, set it to fabric_config
if fabric_config:
if reliability_mode is None:
reliability_mode = ttnn.FabricReliabilityMode.STRICT_INIT
# Apply default logic for fabric_tensix_config,
# fabric_tensix_config is used for enabling tensix extensions for the fabric router,
# some sender channels in the fabric router are moved to the fabric tensix extension
# (currently the extension is mux kernel, can have other kernels in future as well).
if fabric_tensix_config is None:
fabric_tensix_config = get_default_fabric_tensix_config()
if fabric_manager is None:
fabric_manager = ttnn.FabricManagerMode.DEFAULT
# Build kwargs for set_fabric_config, only include fabric_router_config if provided
if fabric_router_config is not None:
ttnn.set_fabric_config(
fabric_config,
reliability_mode,
None,
fabric_tensix_config,
ttnn.FabricUDMMode.DISABLED,
fabric_manager,
fabric_router_config,
)
else:
ttnn.set_fabric_config(
fabric_config,
reliability_mode,
None,
fabric_tensix_config,
ttnn.FabricUDMMode.DISABLED,
fabric_manager,
)
def get_default_fabric_tensix_config():
import ttnn
# Default to DISABLED for all architectures
return ttnn.FabricTensixConfig.DISABLED
@pytest.fixture(scope="function")
def mesh_device(request, silicon_arch_name, device_params):
"""
Pytest fixture to set up a device mesh for tests.
If `request.param` is an integer, it specifies the number of devices to use (up to available devices).
If `request.param` is a tuple, it defines the 2D grid dimensions (rows, columns) for TG, e.g., (8, 4) creates
a devish mesh grid of 8 rows and 4 columns, totaling 32 devices. The total number of devices should not exceed available devices.
Args:
request: Pytest request object.
silicon_arch_name: Name of the silicon architecture.
device_params: Additional device configuration parameters.
Yields:
mesh_device: Initialized device mesh object.
"""
import ttnn
request.node.pci_ids = ttnn.get_pcie_device_ids()
try:
param = request.param
except (ValueError, AttributeError):
# Get number of devices from the system mesh descriptor.
param = ttnn._ttnn.multi_device.SystemMeshDescriptor().shape().mesh_size()
if isinstance(param, tuple):
grid_dims = param
assert len(grid_dims) == 2, "Device mesh grid shape should have exactly two elements."
num_devices_requested = grid_dims[0] * grid_dims[1]
if not ttnn.using_distributed_env() and num_devices_requested > ttnn.get_num_devices():
pytest.skip("Requested more devices than available. Test not applicable for machine")
mesh_shape = ttnn.MeshShape(*grid_dims)
else:
if not ttnn.using_distributed_env() and param > ttnn.get_num_devices():
pytest.skip("Requested more devices than available. Test not applicable for machine")
mesh_shape = ttnn.MeshShape(1, param)
override_trace_region_size = get_supported_trace_region_size(request, param)
if override_trace_region_size:
device_params["trace_region_size"] = override_trace_region_size
logger.info(f"Overriding trace region size to {override_trace_region_size}")
updated_device_params = get_updated_device_params(device_params)
fabric_config = updated_device_params.pop("fabric_config", None)
fabric_tensix_config = updated_device_params.pop("fabric_tensix_config", None)
reliability_mode = updated_device_params.pop("reliability_mode", None)
fabric_manager = updated_device_params.pop("fabric_manager", None)
fabric_router_config = updated_device_params.pop("fabric_router_config", None)
set_fabric(fabric_config, reliability_mode, fabric_tensix_config, fabric_manager, fabric_router_config)
mesh_device = ttnn.open_mesh_device(mesh_shape=mesh_shape, **updated_device_params)
from tests.tests_common.cache_entries_counter import CacheEntriesCounter
mesh_device.cache_entries_counter = CacheEntriesCounter(mesh_device)
logger.debug(f"multidevice with {mesh_device.get_num_devices()} devices is created")
yield mesh_device
for submesh in mesh_device.get_submeshes():
ttnn.close_mesh_device(submesh)
ttnn.close_mesh_device(mesh_device)
reset_fabric(fabric_config)
del mesh_device
@pytest.fixture(scope="function")
def t3k_single_board_mesh_device(request, silicon_arch_name, silicon_arch_wormhole_b0, device_params):
import ttnn
device_ids = ttnn.get_device_ids()
assert len(device_ids) == 8, "This fixture is only applicable for T3K systems"
try:
pcie_id = request.param
except (ValueError, AttributeError):
pcie_id = 0 # Default to using first board
assert pcie_id < 4, "Requested board id is out of range"
mesh_device_ids = [device_ids[pcie_id], device_ids[pcie_id + 4]]
mesh_shape = ttnn.MeshShape(1, 2)
mesh_device = ttnn.open_mesh_device(
mesh_shape, mesh_device_ids, dispatch_core_type=ttnn.device.DispatchCoreType.WORKER, **device_params
)
logger.debug(f"multidevice with {mesh_device.get_num_devices()} devices is created")
yield mesh_device
ttnn.close_mesh_device(mesh_device)
del mesh_device
@pytest.fixture(scope="function")
def pcie_mesh_device(request, silicon_arch_name, silicon_arch_wormhole_b0, device_params):
import ttnn
device_ids = ttnn.get_pcie_device_ids()
try:
num_pcie_devices_requested = min(request.param, len(device_ids))
except (ValueError, AttributeError):
num_pcie_devices_requested = len(device_ids)
if num_pcie_devices_requested != 4:
pytest.skip("Only 4 PCIe devices are supported for testing")
request.node.pci_ids = device_ids[:num_pcie_devices_requested]
updated_device_params = get_updated_device_params(device_params)
fabric_config = updated_device_params.pop("fabric_config", None)
fabric_tensix_config = updated_device_params.pop("fabric_tensix_config", None)
reliability_mode = updated_device_params.pop("reliability_mode", None)
set_fabric(fabric_config, reliability_mode, fabric_tensix_config)
mesh_device = ttnn.open_mesh_device(
mesh_shape=ttnn.MeshShape(2, 2),
**updated_device_params,
offset=ttnn.MeshCoordinate(0, 1),
)
mesh_device.reshape(ttnn.MeshShape(1, 4))
logger.debug(f"multidevice with {mesh_device.get_num_devices()} devices is created")
yield mesh_device
for submesh in mesh_device.get_submeshes():
ttnn.close_mesh_device(submesh)
ttnn.close_mesh_device(mesh_device)
reset_fabric(fabric_config)
del mesh_device
@pytest.fixture(scope="function")
def bh_1d_mesh_device(request, silicon_arch_name, silicon_arch_blackhole, device_params):
# Generic blackhole configuration
# This configures an [m,n] blackhole mesh device to appear as a [1,m*n] line or ring
# Implements wraparound in rackboxes
import ttnn
if ttnn.get_num_devices() not in [1, 2, 4, 8, 32]:
pytest.skip()
request.node.pci_ids = ttnn.get_pcie_device_ids()
updated_device_params = get_updated_device_params(device_params)
fabric_config = updated_device_params.pop("fabric_config", None)
fabric_tensix_config = updated_device_params.pop("fabric_tensix_config", None)
reliability_mode = updated_device_params.pop("reliability_mode", None)
fabric_manager = updated_device_params.pop("fabric_manager", None)
fabric_router_config = updated_device_params.pop("fabric_router_config", None)
set_fabric(fabric_config, reliability_mode, fabric_tensix_config, fabric_manager, fabric_router_config)
mesh_device = ttnn.open_mesh_device(
mesh_shape=ttnn.MeshShape(ttnn.get_num_devices(), 1),
**updated_device_params,
)
logger.debug(f"multidevice with {mesh_device.get_num_devices()} devices is created")
yield mesh_device
for submesh in mesh_device.get_submeshes():
ttnn.close_mesh_device(submesh)
ttnn.close_mesh_device(mesh_device)
reset_fabric(fabric_config)
del mesh_device
@contextlib.contextmanager
def bh_2d_mesh_device_context(device_params):
import ttnn
if ttnn.get_num_devices() not in [1, 2, 4, 8, 32]:
raise RuntimeError("bh_2d_mesh_device requires 1, 2, 4, 8, or 32 devices (got %s)" % ttnn.get_num_devices())
updated_device_params = get_updated_device_params(device_params)
fabric_config = updated_device_params.pop("fabric_config", None)
fabric_tensix_config = updated_device_params.pop("fabric_tensix_config", None)
reliability_mode = updated_device_params.pop("reliability_mode", None)
fabric_manager = updated_device_params.pop("fabric_manager", None)
fabric_router_config = updated_device_params.pop("fabric_router_config", None)
set_fabric(fabric_config, reliability_mode, fabric_tensix_config, fabric_manager, fabric_router_config)
if ttnn.get_num_devices() == 8:
mesh_device = ttnn.open_mesh_device(
mesh_shape=ttnn.MeshShape(4, 2),
**updated_device_params,
)
elif ttnn.get_num_devices() == 32:
mesh_device = ttnn.open_mesh_device(
mesh_shape=ttnn.MeshShape(4, 8),
**updated_device_params,
)
else:
mesh_device = ttnn.open_mesh_device(
mesh_shape=ttnn.MeshShape(ttnn.get_num_devices(), 1),
**updated_device_params,
)
logger.debug(f"multidevice with {mesh_device.get_num_devices()} devices is created")
try:
yield mesh_device
finally:
for submesh in mesh_device.get_submeshes():
ttnn.close_mesh_device(submesh)
ttnn.close_mesh_device(mesh_device)
reset_fabric(fabric_config)
del mesh_device
@pytest.fixture(scope="function")
def bh_2d_mesh_device(request, silicon_arch_name, silicon_arch_blackhole, device_params):
import ttnn
if ttnn.get_num_devices() not in [1, 2, 4, 8, 32]:
pytest.skip()
request.node.pci_ids = ttnn.get_pcie_device_ids()
with bh_2d_mesh_device_context(device_params) as mesh_device:
yield mesh_device
def _check_requires_grid_size(device_or_mesh, marker):
"""Skip the test if device worker grid (compute_with_storage_grid_size) is smaller than required by the mark."""
if marker is None or len(marker.args) == 0:
return
required = marker.args[0]
grid = device_or_mesh.compute_with_storage_grid_size()
if isinstance(required, tuple):
min_x, min_y = required
if grid.x < min_x or grid.y < min_y:
pytest.skip(
f"Test requires device worker grid at least {min_x}x{min_y} but "
f"got {grid.x}x{grid.y} ({grid.x * grid.y} cores)"
)
else:
min_cores = int(required)
total = grid.x * grid.y
if total < min_cores:
pytest.skip(f"Test requires at least {min_cores} worker cores but got {total} ({grid.x}x{grid.y})")
@pytest.fixture(autouse=True)
def check_requires_grid_size(request):
"""Autouse fixture: skips the test when it has requires_grid_size mark and device worker grid is too small. Supports device, bh_2d_mesh_device, and mesh_device. Tests only need @pytest.mark.requires_grid_size((x,y)) or @pytest.mark.requires_grid_size(n_cores)."""
marker = request.node.get_closest_marker("requires_grid_size")
if marker is None:
return
for name in ("bh_2d_mesh_device", "mesh_device", "device"):
if name in request.fixturenames:
device_or_mesh = request.getfixturevalue(name)
_check_requires_grid_size(device_or_mesh, marker)
return
pytest.skip(
"requires_grid_size mark requires one of: device, bh_2d_mesh_device, mesh_device (none requested by test)"
)
requires_hybrid_allocator = pytest.mark.skipif(
os.environ.get("TT_METAL_ALLOCATOR_MODE_HYBRID") != "1",
reason="Test requires TT_METAL_ALLOCATOR_MODE_HYBRID=1 for per-core L1 allocation; "
"the env var must be exported before pytest starts so ttnn.open_device() sees it.",
)
@pytest.fixture()
def ensure_devices_tg():
import ttnn
device_ids = ttnn.get_device_ids()
assert len(device_ids) == 32, f"Expected 32 devices, got {len(device_ids)}"
@pytest.fixture(autouse=True)
def reset_default_device(request):
import ttnn
# Skip applying the fixture logic for this test
if "no_reset_default_device" in request.keywords:
yield
return
try:
device = ttnn.GetDefaultDevice()
except Exception:
logger.warning("Device handle is stale/crashed - setting saved device to None")
device = None
yield
if device is not None:
ttnn.SetDefaultDevice(device)
elif "device" in request.fixturenames:
# if the test used a device, but there was no default device, we need to clear the default device
ttnn.SetDefaultDevice(None)
def get_devices(request):
if "device" in request.fixturenames:
devices = [request.getfixturevalue("device")]
elif "mesh_device" in request.fixturenames:
devices = [request.getfixturevalue("mesh_device")]
elif "pcie_mesh_device" in request.fixturenames:
devices = [request.getfixturevalue("pcie_mesh_device")]
elif "t3k_single_board_mesh_device" in request.fixturenames:
devices = request.getfixturevalue("t3k_single_board_mesh_device").get_devices()
else:
devices = []
return devices
@pytest.fixture(scope="function")
def tracy_profile():
from tracy import Profiler
profiler = Profiler()
profiler.enable()
yield
profiler.disable()
###############################
# Modifying pytest hooks
###############################
ALL_ARCHS = set(
[
"grayskull",
"wormhole_b0",
"blackhole",
]
)
def pytest_addoption(parser):
import ttnn
parser.addoption(
"--tt-arch",
choices=[*ALL_ARCHS],
default=ttnn.get_arch_name(),
help="Target arch, ex. grayskull, wormhole_b0, blackhole",
)
parser.addoption(
"--pipeline-type",
default="",
help="Only `models_device_performance_bare_metal` should run `pytest_runtest_teardown`",
)
parser.addoption(
"--device-id",
type=int,
default=0,
help="Target device id",
)
parser.addoption(
"--input-method",
action="store",
choices=["json", "cli"],
default=None,
help="Choose input method: 1) json or 2) cli",
)
parser.addoption(
"--input-path",
action="store",
default="",
help="Path to json file with inputs",
)
parser.addoption("--cli-input", action="store", default=None, help="Enter prompt if --input-method=cli")
parser.addoption(
"--didt-workload-iterations",
action="store",
default=None,
help="Number of workload iterations to run for didt tests",
)
parser.addoption(
"--determinism-check-interval",
action="store",
default=None,
help="Check determinism every nth iteration",
)
parser.addoption(
"--grid-size",
action="store",
default=None,
help="Size of chip grid for the test to run on. Grid size is defined by number of cores in row x number of cores in column, e.g., 8x8",
)
@pytest.fixture
def grid_size(request):
"""
Fixture to set the chip grid size for the test to run on.
If --grid-size is provided, it returns a tuple of integers (rows, columns).
If not provided, it defaults to None.
"""
grid_size_str = request.config.getoption("--grid-size")
if grid_size_str:
try:
rows, cols = map(int, grid_size_str.split("x"))
return (rows, cols)
except ValueError:
raise ValueError(f"Invalid grid size format: {grid_size_str}. Use format 'rows x cols'.")
return None
# Indicates the iteration interval at which determinism is verified for the op output
@pytest.fixture
def determinism_check_interval(request):
iterations = request.config.getoption("--determinism-check-interval")
if iterations is not None:
# this will throw an error if bad value is passed
return int(iterations)
return -1
# Indicated the number of workload iterations to run within didt tests
@pytest.fixture
def didt_workload_iterations(request):
iterations = request.config.getoption("--didt-workload-iterations")
if iterations is not None:
# this will throw an error if bad value is passed
return int(iterations)
# default is 100000
return 100000
@pytest.fixture
def input_path(request):
return request.config.getoption("--input-path")
def pytest_generate_tests(metafunc):
"""
This is not a standard docstring.
We will explain the non-standard fixtures that pytest_generate_tests is
creating here.
silicon_arch_name and silicon_arch_<ARCH_NAME>
----------------------------------------------
This is how tests should be requesting accelerator architecture names.
Tests which aim to run on silicon should request a silicon_arch_name
fixture. Just that single fixture will parametrize the test to run on the
provided architecture name from the command line through the --tt-arch
option. The value of the fixture will be the string value of the
architecture name. For example,
@pytest.mark.post_commit
def test_model_silicon(silicon_arch_name):
# silicon_arch_name will be one of grayskull, wormhole_b0 etc.
run_model_on_silicon(silicon_arch_name)
...
If you want to restrict a test to only a specific architecture, you can
provide an additional fixture in the form of silicon_arch_<ARCH_NAME>. This
will limit the range of possible values for silicon_arch_name to only be
ARCH_NAME.
@pytest.mark.post_commit
def test_model_silicon_grayskull_only(
silicon_arch_name,
silicon_arch_grayskull,
):
# silicon_arch_name can only be grayskull or empty
run_model_on_silicon(silicon_arch_name)
...
If --tt-arch specifies an architecture that's not ARCH_NAME, the test will
be skipped. We ensure skipping by providing an empty list parametrization
for silicon_arch_name, and with the empty_parameter_set_mark config option
for pytest, will skip any tests with an empty list parametrization.
Note that you must provide silicon_arch_name as a fixture if you want to
use the silicon_arch_<ARCH_NAME> fixture.
Note that if tests want to use the ARCH value from the API, tests should
create their own separate fixture which will convert the string value