Skip to content

Commit cba59ec

Browse files
authored
add core.testing for torch ut (#2136)
1 parent daf575f commit cba59ec

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+38623
-3814
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,4 +172,5 @@ tests/transformers/
172172
tests/huggingface_transformers/
173173
.gradio/
174174

175-
huanhuan.json
175+
huanhuan.json
176+
pytorch/

examples/transformers/inference/gpt-oss/gpt_oss_standalone.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import mindnlp
2-
from mindnlp.core import distributed as dist
32
from transformers import AutoModelForCausalLM, AutoTokenizer
43

54
model_id = "openai/gpt-oss-20b"

examples/transformers/peft/lora/Qwen2.5-7B-Instruct-Lora.ipynb

Lines changed: 19954 additions & 3708 deletions
Large diffs are not rendered by default.

mindnlp/core/_C/__init__.py

Lines changed: 81 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,18 @@
1+
from typing import Any
12
from mindspore import Generator as msGenerator
3+
import mindspore
24

5+
from mindnlp import core
36
from . import _nn
4-
from ..types import device as device_
57
from ..configs import DEVICE_TARGET
68

9+
DEVICE_MAP = {
10+
'GPU': 'cuda',
11+
'Ascend': 'npu',
12+
'CPU': 'cpu'
13+
}
14+
15+
716
def _jit_set_profiling_executor(mode):
817
pass
918

@@ -30,6 +39,72 @@ def _debug_set_autodiff_subgraph_inlining(mode):
3039

3140
DisableTorchFunctionSubclass = None
3241

42+
43+
class device():
44+
def __init__(self, type=None, index=None):
45+
if type is not None:
46+
if isinstance(type, str):
47+
if ':' in type:
48+
if index is not None:
49+
raise ValueError("`type` must not include an index because index was "
50+
f"passed explicitly: {type}")
51+
_target, _id = type.split(':')
52+
_id = int(_id)
53+
else:
54+
_target = type
55+
_id = None if _target == 'cpu' else 0
56+
elif isinstance(type, device):
57+
if index is not None:
58+
raise ValueError("core.device(): When input is core.device, `index` can not be set.")
59+
_target = type.type
60+
_id = type.index
61+
elif isinstance(type, int):
62+
_id = type
63+
try:
64+
device_target = mindspore.get_current_device().device_target
65+
except:
66+
device_target = mindspore.get_context('device_target')
67+
_target = DEVICE_MAP[device_target]
68+
else:
69+
print(type)
70+
raise TypeError("core.device(): `type` must be type of 'str' or 'core.device'.")
71+
else:
72+
raise ValueError("core.device(): `type` can not be None")
73+
74+
self.type = _target
75+
self.index = _id
76+
if DEVICE_TARGET == 'Ascned' and self.type == 'cuda':
77+
self.type = 'npu'
78+
79+
def __repr__(self):
80+
if self.index is None:
81+
return f"device(type={self.type})"
82+
return f"device(type={self.type}, index={self.index})"
83+
84+
def __eq__(self, __value):
85+
if not isinstance(__value, device):
86+
return False
87+
return hash(self) == hash(__value)
88+
89+
def __hash__(self):
90+
return hash(self.type) ^ hash(self.index)
91+
92+
def __gt__(self, other):
93+
if self.type == 'cpu':
94+
return False
95+
return True
96+
97+
def __enter__(self):
98+
# self.prev_idx = torch.cuda._exchange_device(self.idx)
99+
core._bind.set_device_in_context(self)
100+
101+
def __exit__(self, type: Any, value: Any, traceback: Any):
102+
# self.idx = torch.cuda._maybe_exchange_device(self.prev_idx)
103+
core._bind.set_device_in_context(None)
104+
return False
105+
106+
device_ = device
107+
33108
class Generator(msGenerator):
34109
def __init__(self, device='cpu'):
35110
super().__init__()
@@ -41,11 +116,14 @@ def __init__(self, device='cpu'):
41116
def device(self):
42117
if hasattr(self, '_device'):
43118
return self._device
44-
return device_('cpu')
119+
return device('cpu')
45120

46121
default_generator = Generator()
47122

48123
class Tag: pass
49124

50125
def _log_api_usage_once(*args):
51-
pass
126+
pass
127+
128+
ScriptDict = dict
129+
ScriptList = list

mindnlp/core/_C/_nn.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
from mindnlp import core
2-
from ..types import device as device_
32

43
def _parse_to(*args, **kwargs):
54
"""
@@ -22,7 +21,7 @@ def _parse_to(*args, **kwargs):
2221
device = args[0]
2322
dtype = None
2423
elif isinstance(args[0], (str, int)):
25-
device = device_(args[0])
24+
device = core.device(args[0])
2625
dtype = None
2726
else:
2827
raise TypeError(f"Expected core.dtype or core.device, but got {type(args[0])}")

mindnlp/core/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,17 +36,16 @@
3636
preserve_format = None
3737
legacy_contiguous_format = None
3838
channels_last_3d = None
39+
memory_format = None
3940

4041
inf = float("inf")
4142
nan = float("nan")
4243

43-
from ._C import *
4444
from ._dtype import *
4545
from ._tensor import Tensor, tensor, is_tensor, \
4646
LongTensor, FloatTensor, BoolTensor, HalfTensor, BFloat16Tensor, IntTensor
47-
from .types import device
47+
from ._C import *
4848
from ._C.size import Size
49-
from .types import device
5049
from .autograd import *
5150
from .ops import *
5251
from .serialization import load, save
@@ -57,8 +56,9 @@
5756
from .func import vmap
5857
from .configs import set_pyboost
5958

59+
from . import _dynamo
6060
from . import profiler, cuda, amp, compiler, jit, version, __future__, overrides, \
61-
return_types, linalg, fx, backends, testing, nn, fft, _jit_internal, utils, optim
61+
return_types, linalg, fx, backends, nn, fft, _jit_internal, utils, optim, testing
6262
from ._lowrank import svd_lowrank
6363
from .random import get_rng_state, initial_seed, manual_seed, seed, set_rng_state
6464

mindnlp/core/_bind.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import ctypes
22
from typing import Any
33
from ._dtype import *
4-
from .types import device as device_
4+
from ._C import device as device_
55
from .configs import ON_A1
66

77
DEFAULT_DTYPE, DEFAULT_DEVICE = float32, device_('cpu')

mindnlp/core/_dtype.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,11 @@ def __gt__(self, other):
4646

4747
float8_e4m3fn = None # TODO: not support fp8 for now
4848
float8_e5m2 = None
49+
float8_e4m3fnuz = None
50+
float8_e5m2fnuz = None
51+
complex32 = None
52+
cfloat = complex32
53+
cdouble = complex64
4954

5055
uint1 = None
5156
uint2 = None

mindnlp/core/_dynamo/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
)
2121

2222
from . import eval_frame
23+
# from . import config
2324

2425
def reset():
2526
pass

0 commit comments

Comments
 (0)