netcl-py36 0.6.1__py36-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.
Files changed (190) hide show
  1. netcl/__init__.py +9 -0
  2. netcl/_legacy_compat.py +41 -0
  3. netcl/amp.py +133 -0
  4. netcl/autograd/__init__.py +11 -0
  5. netcl/autograd/bf16_ops.py +122 -0
  6. netcl/autograd/compiler.py +469 -0
  7. netcl/autograd/debug.py +9 -0
  8. netcl/autograd/engine.py +448 -0
  9. netcl/autograd/forward_compiler.py +215 -0
  10. netcl/autograd/graph.py +130 -0
  11. netcl/autograd/ops.py +2343 -0
  12. netcl/autograd/shape_ops.py +344 -0
  13. netcl/autograd/training_compiler.py +166 -0
  14. netcl/cluster/__init__.py +35 -0
  15. netcl/cluster/dbscan.py +90 -0
  16. netcl/cluster/gmm.py +153 -0
  17. netcl/cluster/kmeans.py +302 -0
  18. netcl/cluster/metrics.py +223 -0
  19. netcl/cluster/ops.py +572 -0
  20. netcl/cluster/spectral.py +148 -0
  21. netcl/core/__init__.py +7 -0
  22. netcl/core/autotune.py +184 -0
  23. netcl/core/backend/__init__.py +40 -0
  24. netcl/core/backend/base.py +57 -0
  25. netcl/core/backend/cpu.py +40 -0
  26. netcl/core/backend/opencl.py +367 -0
  27. netcl/core/backend/vulkan.py +997 -0
  28. netcl/core/backend/vulkan_caps.py +59 -0
  29. netcl/core/backend/vulkan_conv.py +156 -0
  30. netcl/core/backend/vulkan_gemm.py +571 -0
  31. netcl/core/backend/vulkan_loss.py +78 -0
  32. netcl/core/backend/vulkan_norm.py +201 -0
  33. netcl/core/backend/vulkan_ops.py +1166 -0
  34. netcl/core/backend/vulkan_spirv.py +1645 -0
  35. netcl/core/backend/vulkan_spirv_ops.py +2549 -0
  36. netcl/core/backend/vulkan_winograd.py +317 -0
  37. netcl/core/bindings/__init__.py +7 -0
  38. netcl/core/bindings/_ffi.py +129 -0
  39. netcl/core/bindings/debug.py +42 -0
  40. netcl/core/bindings/opencl/__init__.py +16 -0
  41. netcl/core/bindings/opencl/_generated.py +616 -0
  42. netcl/core/bindings/opencl/_info.py +33 -0
  43. netcl/core/bindings/opencl/_lib.py +44 -0
  44. netcl/core/bindings/opencl/api.py +330 -0
  45. netcl/core/bindings/opencl/errors.py +43 -0
  46. netcl/core/bindings/opencl/events.py +158 -0
  47. netcl/core/bindings/opencl/memory.py +203 -0
  48. netcl/core/bindings/opencl/program.py +378 -0
  49. netcl/core/bindings/opencl/svm.py +166 -0
  50. netcl/core/bindings/vulkan/__init__.py +17 -0
  51. netcl/core/bindings/vulkan/_generated.py +2716 -0
  52. netcl/core/bindings/vulkan/_lib.py +72 -0
  53. netcl/core/bindings/vulkan/api.py +122 -0
  54. netcl/core/bindings/vulkan/errors.py +42 -0
  55. netcl/core/capabilities.py +269 -0
  56. netcl/core/device.py +195 -0
  57. netcl/core/device_profile.py +231 -0
  58. netcl/core/kernel_selector.py +220 -0
  59. netcl/core/kernels/__init__.py +5 -0
  60. netcl/core/kernels/primitives.py +102 -0
  61. netcl/core/kernels/typed.py +85 -0
  62. netcl/core/memory.py +649 -0
  63. netcl/core/parameter.py +74 -0
  64. netcl/core/precision.py +91 -0
  65. netcl/core/shape.py +81 -0
  66. netcl/core/tensor.py +352 -0
  67. netcl/core/transfer.py +184 -0
  68. netcl/data/augment.py +37 -0
  69. netcl/data/augment_gpu.py +111 -0
  70. netcl/data/dataloader.py +310 -0
  71. netcl/data/filters.py +79 -0
  72. netcl/data/gpu_batch.py +77 -0
  73. netcl/data/shared_batch.py +131 -0
  74. netcl/distributed/__init__.py +8 -0
  75. netcl/distributed/collectives.py +123 -0
  76. netcl/distributed/data_parallel.py +47 -0
  77. netcl/distributed/device_manager.py +22 -0
  78. netcl/distributed/trainer.py +45 -0
  79. netcl/evo/__init__.py +40 -0
  80. netcl/evo/benchmarks.py +48 -0
  81. netcl/evo/engine.py +263 -0
  82. netcl/evo/fitness.py +184 -0
  83. netcl/evo/genome.py +352 -0
  84. netcl/evo/ops.py +540 -0
  85. netcl/evo/population.py +241 -0
  86. netcl/evo/random.py +73 -0
  87. netcl/evo/strategies.py +435 -0
  88. netcl/io/__init__.py +25 -0
  89. netcl/io/checkpoint.py +61 -0
  90. netcl/io/interop.py +385 -0
  91. netcl/io/onnx_export.py +139 -0
  92. netcl/io/serialization.py +101 -0
  93. netcl/nn/__init__.py +39 -0
  94. netcl/nn/batchnorm.py +441 -0
  95. netcl/nn/containers.py +492 -0
  96. netcl/nn/decorators.py +37 -0
  97. netcl/nn/factory.py +151 -0
  98. netcl/nn/functional.py +142 -0
  99. netcl/nn/groupnorm.py +132 -0
  100. netcl/nn/init.py +74 -0
  101. netcl/nn/layernorm.py +96 -0
  102. netcl/nn/layers.py +970 -0
  103. netcl/nn/loss.py +72 -0
  104. netcl/nn/margin.py +268 -0
  105. netcl/nn/modern.py +309 -0
  106. netcl/nn/modules.py +75 -0
  107. netcl/nn/padding.py +122 -0
  108. netcl/nn/pooling.py +344 -0
  109. netcl/nn/residual.py +19 -0
  110. netcl/nn/resnet.py +151 -0
  111. netcl/nn/simple.py +30 -0
  112. netcl/nn/state.py +282 -0
  113. netcl/nn/transformer.py +168 -0
  114. netcl/ops/__init__.py +15 -0
  115. netcl/ops/attention.py +151 -0
  116. netcl/ops/bf16_act.py +131 -0
  117. netcl/ops/bmm.py +85 -0
  118. netcl/ops/broadcast.py +75 -0
  119. netcl/ops/conv2d.py +1056 -0
  120. netcl/ops/conv2d_cpu.py +176 -0
  121. netcl/ops/conv2d_dilated.py +287 -0
  122. netcl/ops/conv2d_optimized.py +514 -0
  123. netcl/ops/conv2d_planner.py +1210 -0
  124. netcl/ops/conv2d_pointwise.py +249 -0
  125. netcl/ops/conv_bf16.py +208 -0
  126. netcl/ops/conv_transpose2d.py +112 -0
  127. netcl/ops/depthwise_conv2d.py +213 -0
  128. netcl/ops/elementwise.py +1006 -0
  129. netcl/ops/elementwise_optimized.py +167 -0
  130. netcl/ops/fused_ops.py +150 -0
  131. netcl/ops/grid_sample.py +236 -0
  132. netcl/ops/im2col.py +153 -0
  133. netcl/ops/indexing.py +169 -0
  134. netcl/ops/jit_fusion.py +176 -0
  135. netcl/ops/lm_ops.py +150 -0
  136. netcl/ops/matmul.py +411 -0
  137. netcl/ops/matmul_optimized.py +457 -0
  138. netcl/ops/norm_rope.py +113 -0
  139. netcl/ops/permute.py +87 -0
  140. netcl/ops/reduction.py +125 -0
  141. netcl/ops/softmax.py +175 -0
  142. netcl/ops/softmax_fp16.py +22 -0
  143. netcl/ops/softmax_fused.py +79 -0
  144. netcl/ops/tc_gemm.py +200 -0
  145. netcl/ops/tensor_ops.py +313 -0
  146. netcl/ops/transpose.py +60 -0
  147. netcl/ops/upsample.py +178 -0
  148. netcl/ops/winograd_bf16.py +100 -0
  149. netcl/ops/winograd_fused.py +75 -0
  150. netcl/optim/__init__.py +11 -0
  151. netcl/optim/_utils.py +6 -0
  152. netcl/optim/adam.py +137 -0
  153. netcl/optim/adamw.py +572 -0
  154. netcl/optim/amp.py +42 -0
  155. netcl/optim/clip.py +116 -0
  156. netcl/optim/ema.py +131 -0
  157. netcl/optim/lr_plateau.py +68 -0
  158. netcl/optim/lr_scheduler.py +14 -0
  159. netcl/optim/momentum.py +41 -0
  160. netcl/optim/rmsprop.py +59 -0
  161. netcl/optim/sgd.py +158 -0
  162. netcl/profiling/__init__.py +5 -0
  163. netcl/profiling/autotuner.py +335 -0
  164. netcl/profiling/timing.py +23 -0
  165. netcl/runtime/__init__.py +7 -0
  166. netcl/runtime/cache.py +44 -0
  167. netcl/runtime/capture.py +257 -0
  168. netcl/runtime/graph.py +117 -0
  169. netcl/runtime/graph_fusion.py +277 -0
  170. netcl/runtime/perf.py +21 -0
  171. netcl/runtime/scheduler.py +47 -0
  172. netcl/ssl/__init__.py +44 -0
  173. netcl/ssl/deep_cluster.py +261 -0
  174. netcl/ssl/evaluate.py +154 -0
  175. netcl/ssl/heads.py +190 -0
  176. netcl/ssl/losses.py +242 -0
  177. netcl/ssl/methods.py +338 -0
  178. netcl/ssl/views.py +312 -0
  179. netcl/text/__init__.py +4 -0
  180. netcl/text/bpe.py +170 -0
  181. netcl/text/chat.py +103 -0
  182. netcl/trainer/__init__.py +2 -0
  183. netcl/trainer/trainer.py +282 -0
  184. netcl/utils/__init__.py +3 -0
  185. netcl/utils/data.py +22 -0
  186. netcl/utils/progress.py +92 -0
  187. netcl_py36-0.6.1.dist-info/METADATA +167 -0
  188. netcl_py36-0.6.1.dist-info/RECORD +190 -0
  189. netcl_py36-0.6.1.dist-info/WHEEL +5 -0
  190. netcl_py36-0.6.1.dist-info/top_level.txt +1 -0
netcl/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """
2
+ Tensor operations, autograd and neural networks on OpenCL, Vulkan and NumPy.
3
+ """
4
+ from . import core, ops, autograd, distributed, runtime, profiling
5
+ from .ops import matmul, build_matmul_kernel, elementwise_binary, relu, bias_add, reduce_sum, softmax, conv2d, grid_sample, affine_grid, index_add, scatter_add
6
+ from .core.device import device, set_default_backend, get_default_backend
7
+ from .core.precision import get_matmul_precision, set_matmul_precision
8
+ from . import nn, optim, io, evo, cluster, ssl
9
+ __all__ = ['set_default_backend', 'get_default_backend', 'set_matmul_precision', 'get_matmul_precision', 'core', 'ops', 'autograd', 'distributed', 'runtime', 'profiling', 'nn', 'optim', 'io', 'evo', 'cluster', 'ssl', 'matmul', 'build_matmul_kernel', 'elementwise_binary', 'relu', 'bias_add', 'reduce_sum', 'softmax', 'conv2d', 'grid_sample', 'affine_grid', 'index_add', 'scatter_add', 'device']
@@ -0,0 +1,41 @@
1
+ """Stand-ins for standard-library names newer than Python 3.6.
2
+
3
+ Generated by tools/legacy_wheel/backport.py for the legacy (Python 3.6-3.9)
4
+ wheel of netcl. Each name is the standard-library one when it exists.
5
+ """
6
+ import contextlib as _contextlib
7
+ import math as _math
8
+
9
+ try:
10
+ from multiprocessing.shared_memory import SharedMemory as _SharedMemory # noqa: F401
11
+ HAS_SHARED_MEMORY = True
12
+ except ImportError:
13
+ HAS_SHARED_MEMORY = False
14
+
15
+ if hasattr(_math, "lcm"):
16
+ lcm = _math.lcm
17
+ else:
18
+ def lcm(*integers):
19
+ """Least common multiple, as math.lcm (Python 3.9)."""
20
+ result = 1
21
+ for value in integers:
22
+ value = int(value)
23
+ if value == 0:
24
+ return 0
25
+ result = abs(result * value) // _math.gcd(result, value)
26
+ return result
27
+
28
+ if hasattr(_contextlib, "nullcontext"):
29
+ nullcontext = _contextlib.nullcontext
30
+ else:
31
+ class nullcontext(object):
32
+ """Context manager that does nothing, as contextlib.nullcontext (3.7)."""
33
+
34
+ def __init__(self, enter_result=None):
35
+ self.enter_result = enter_result
36
+
37
+ def __enter__(self):
38
+ return self.enter_result
39
+
40
+ def __exit__(self, *exc_info):
41
+ return False
netcl/amp.py ADDED
@@ -0,0 +1,133 @@
1
+ from dataclasses import dataclass
2
+ from typing import Optional, Sequence
3
+ try:
4
+ import numpy as np
5
+ except ImportError:
6
+ np = None
7
+ from netcl.core.tensor import Tensor
8
+ from netcl.core.tensor import _np_dtype
9
+ _AUTOCAST_ENABLED = False
10
+
11
+ @dataclass
12
+ class GradScaler:
13
+ init_scale: 'float' = 2.0 ** 16
14
+ growth_factor: 'float' = 2.0
15
+ backoff_factor: 'float' = 0.5
16
+ growth_interval: 'int' = 2000
17
+ enabled: 'bool' = True
18
+
19
+ def __post_init__(self):
20
+ self._scale = self.init_scale
21
+ self._growth_tracker = 0
22
+
23
+ @property
24
+ def scale(self):
25
+ return self._scale
26
+
27
+ def scale_loss(self, loss):
28
+ if not self.enabled:
29
+ return loss
30
+ from netcl.ops.elementwise import elementwise_binary
31
+ return elementwise_binary(loss, loss, expression='MUL(v0, {})'.format(float(self._scale)))
32
+
33
+ def unscale_grads(self, params):
34
+ if not self.enabled:
35
+ return False
36
+ found_inf = False
37
+ for p in params:
38
+ if p.grad is None:
39
+ continue
40
+ g = p.grad.to_host()
41
+ if np.any(~np.isfinite(g)):
42
+ found_inf = True
43
+ break
44
+ if not found_inf:
45
+ inv_scale = 1.0 / self._scale
46
+ from netcl.ops.elementwise import elementwise_binary
47
+ for p in params:
48
+ if p.grad is None:
49
+ continue
50
+ p.grad = elementwise_binary(p.grad, p.grad, expression='MUL(v0, {})'.format(inv_scale))
51
+ return found_inf
52
+
53
+ def step(self, optimizer, params):
54
+ if not self.enabled:
55
+ optimizer.step()
56
+ return
57
+ found_inf = self.unscale_grads(params)
58
+ if not found_inf:
59
+ optimizer.step()
60
+ self._growth_tracker += 1
61
+ if self._growth_tracker % self.growth_interval == 0:
62
+ self._scale *= self.growth_factor
63
+ else:
64
+ self._scale *= self.backoff_factor
65
+ self._growth_tracker = 0
66
+
67
+ def update(self):
68
+ pass
69
+
70
+ def supports_fp16(queue):
71
+ """
72
+ Check device extensions for cl_khr_fp16 support.
73
+ """
74
+ try:
75
+ return 'cl_khr_fp16' in queue.device.extensions
76
+ except Exception:
77
+ return False
78
+
79
+ def autocast_enabled(profile_supports_fp16):
80
+ return profile_supports_fp16
81
+
82
+ class autocast:
83
+ """
84
+ Context manager for autocast. Enables casting only if underlying device supports fp16.
85
+ """
86
+
87
+ def __init__(self, enabled=True, device_queue=None):
88
+ self.enabled = enabled
89
+ self.device_queue = device_queue
90
+ self.prev = False
91
+ self._capable = True
92
+
93
+ def __enter__(self):
94
+ global _AUTOCAST_ENABLED
95
+ self.prev = _AUTOCAST_ENABLED
96
+ if not self.enabled:
97
+ _AUTOCAST_ENABLED = False
98
+ return self
99
+ if self.device_queue is not None:
100
+ self._capable = supports_fp16(self.device_queue)
101
+ _AUTOCAST_ENABLED = self.enabled and self._capable
102
+ return self
103
+
104
+ def __exit__(self, exc_type, exc_val, exc_tb):
105
+ global _AUTOCAST_ENABLED
106
+ _AUTOCAST_ENABLED = self.prev
107
+ return False
108
+
109
+ def is_autocast_enabled():
110
+ return _AUTOCAST_ENABLED
111
+
112
+ def maybe_cast_tensor(t):
113
+ if not _AUTOCAST_ENABLED:
114
+ return t
115
+ if t.dtype in ('float', 'float32'):
116
+ if supports_fp16(t.queue):
117
+ arr = t.to_host().astype(np.float16)
118
+ return Tensor.from_host(t.queue, arr, dtype='float16')
119
+ return t
120
+ return t
121
+
122
+ def master_param(param):
123
+ """
124
+ Keep master weights in FP32 for optimizers.
125
+ """
126
+ if param.dtype in ('float16', 'half'):
127
+ master = Tensor.from_host(param.queue, param.to_host().astype(np.float32), dtype='float32')
128
+ master.requires_grad = getattr(param, 'requires_grad', True)
129
+ master._frozen = getattr(param, '_frozen', False)
130
+ setattr(master, '_model_param', param)
131
+ return master
132
+ setattr(param, '_model_param', param)
133
+ return param
@@ -0,0 +1,11 @@
1
+ """
2
+ Autograd: Node/Tape plus op wrappers.
3
+ """
4
+ from .engine import Node, Tape, apply_op, no_grad, set_current_tape, get_current_tape, set_detect_anomaly, detect_anomaly, is_grad_enabled, set_grad_enabled
5
+ from .compiler import jit_compile
6
+ from .training_compiler import TrainingGraphCompiler, TrainingPattern, fused_weighted_bce_smooth_l1_loss, get_training_compiler
7
+ from .graph import CompiledGraph
8
+ from .shape_ops import cat, stack, narrow, split, chunk, reshape, unsqueeze, squeeze, getitem, upsample, interpolate, grid_sample, affine_grid, rotate_2d_grid, index_select, index_add, scatter_add, embedding, gather, one_hot, argmax, topk, masked_fill, cross_entropy_indices, causal_mask, arange, rms_norm, rope, flash_attention
9
+ from .debug import debug_tape
10
+ from .ops import tensor, add, relu, add_relu, bias_add, matmul_op, matmul_op as matmul, linear_relu, sub, mul, div, abs, maximum, minimum, square, exp, log, log1p, sqrt, rsqrt, pow, clip, lt, le, gt, ge, where, sum, mean, mse_loss, sigmoid, tanh, leaky_relu, gelu, swish, elu, softplus, hard_sigmoid, hard_swish, clamp, hard_tanh, prelu, hinge_loss, l1_loss, l2_loss, smooth_l1_loss, weighted_smooth_l1_loss, weighted_smooth_l1_elementwise, weighted_bce, weighted_bce_elementwise, depthwise_conv2d, conv_transpose2d, batch_norm2d, batch_norm2d_relu, batch_norm2d_leaky_relu, layer_norm, pad2d, group_norm, global_avg_pool2d, cross_entropy, binary_cross_entropy, binary_cross_entropy_with_logits, conv2d, conv2d_relu, flatten, max_pool2d, dropout, avg_pool2d, permute, bmm, softmax, triplet_loss, info_nce_loss, pairwise_squared_distances, batch_hard_triplet_loss, l2_normalize, contrastive_loss, batch_all_triplet_loss
11
+ __all__ = ['Node', 'Tape', 'apply_op', 'no_grad', 'tensor', 'add', 'relu', 'add_relu', 'bias_add', 'matmul_op', 'linear_relu', 'sub', 'mul', 'div', 'abs', 'maximum', 'minimum', 'square', 'exp', 'log', 'log1p', 'sqrt', 'rsqrt', 'pow', 'clip', 'lt', 'le', 'gt', 'ge', 'where', 'sum', 'mean', 'mse_loss', 'sigmoid', 'tanh', 'leaky_relu', 'gelu', 'swish', 'elu', 'softplus', 'hard_sigmoid', 'hard_swish', 'clamp', 'hard_tanh', 'prelu', 'hinge_loss', 'l1_loss', 'l2_loss', 'smooth_l1_loss', 'weighted_smooth_l1_loss', 'weighted_smooth_l1_elementwise', 'weighted_bce', 'weighted_bce_elementwise', 'TrainingGraphCompiler', 'TrainingPattern', 'fused_weighted_bce_smooth_l1_loss', 'get_training_compiler', 'depthwise_conv2d', 'conv_transpose2d', 'batch_norm2d', 'batch_norm2d_relu', 'batch_norm2d_leaky_relu', 'layer_norm', 'pad2d', 'group_norm', 'global_avg_pool2d', 'cross_entropy', 'binary_cross_entropy', 'binary_cross_entropy_with_logits', 'conv2d', 'conv2d_relu', 'flatten', 'max_pool2d', 'dropout', 'avg_pool2d', 'permute', 'bmm', 'softmax', 'triplet_loss', 'info_nce_loss', 'pairwise_squared_distances', 'batch_hard_triplet_loss', 'l2_normalize', 'contrastive_loss', 'batch_all_triplet_loss', 'debug_tape', 'set_current_tape', 'get_current_tape', 'jit_compile', 'CompiledGraph', 'set_detect_anomaly', 'detect_anomaly', 'is_grad_enabled', 'set_grad_enabled', 'cat', 'stack', 'narrow', 'split', 'chunk', 'reshape', 'unsqueeze', 'squeeze', 'getitem', 'upsample', 'interpolate', 'grid_sample', 'affine_grid', 'rotate_2d_grid', 'index_select', 'index_add', 'scatter_add', 'matmul', 'embedding', 'gather', 'one_hot', 'argmax', 'topk', 'masked_fill', 'cross_entropy_indices', 'causal_mask', 'arange', 'rms_norm', 'rope', 'flash_attention']
@@ -0,0 +1,122 @@
1
+ """
2
+ Autograd ops on bf16 activations (see netcl.ops.bf16_act / netcl.ops.conv_bf16).
3
+
4
+ Routing: with matmul precision "medium" on a device whose tensor cores run
5
+ bf16 (netcl.core.precision.bf16_activations) and gradients enabled, ag.conv2d
6
+ produces bf16 activations; BatchNorm2d, PReLU and add keep them bf16. Any
7
+ other op that receives a bf16 activation gets it cast back to float32 first
8
+ (engine.apply_op), so models need no changes and every op without a bf16
9
+ kernel keeps working. Parameters, parameter gradients and BN statistics stay
10
+ float32. Inference under no_grad stays entirely float32.
11
+ """
12
+ from netcl.autograd.engine import Node, apply_op, is_grad_enabled
13
+ from netcl.core.tensor import Tensor
14
+ BF16 = 'bfloat16'
15
+
16
+ def is_bf16(node):
17
+ v = getattr(node, 'value', None)
18
+ return isinstance(v, Tensor) and v.dtype == BF16
19
+
20
+ def active(t):
21
+ if not isinstance(t, Tensor) or not is_grad_enabled() or getattr(t, 'backend', 'cl') == 'cpu':
22
+ return False
23
+ try:
24
+ from netcl.autograd.compiler import get_tracing_context
25
+ if get_tracing_context().active:
26
+ return False
27
+ except Exception:
28
+ pass
29
+ from netcl.core.precision import bf16_activations
30
+ return bf16_activations(t.queue)
31
+
32
+ def _bf16_grad(g):
33
+ from netcl.ops import bf16_act as B
34
+ return g if g.dtype == BF16 else B.cast(g, BF16)
35
+
36
+ def cast(x, dtype, tape=None):
37
+ from netcl.ops import bf16_act as B
38
+ src = x.value.dtype
39
+
40
+ def grad_fn(g):
41
+ return [g if g.dtype == src else B.cast(g, src)]
42
+ return apply_op(lambda t: B.cast(t, dtype), grad_fn, x, tape=tape, op_name='cast_{}'.format(dtype), bf16_ok=True)
43
+
44
+ def route_conv(x, w, bias, stride, pad, dilation, groups, algo):
45
+ xv, wv = (getattr(x, 'value', None), getattr(w, 'value', None))
46
+ return bias is None and groups == 1 and (dilation == 1) and (algo is None) and isinstance(xv, Tensor) and isinstance(wv, Tensor) and (len(xv.shape) == 4) and (len(wv.shape) == 4) and (wv.dtype in ('float32', 'float')) and (xv.dtype in (BF16, 'float32', 'float')) and active(xv)
47
+
48
+ def conv2d(x, w, stride=1, pad=0, tape=None):
49
+ from netcl.ops import conv_bf16 as CB
50
+ need_x = bool(getattr(x, 'requires_grad', True)) or getattr(x, 'grad_fn', None) is not None
51
+ if x.value.dtype != BF16:
52
+ x = cast(x, BF16, tape=tape)
53
+ x_shape = x.value.shape
54
+
55
+ def grad_fn(g):
56
+ g = _bf16_grad(g)
57
+ gx = CB.conv2d_grad_x(g, w.value, x_shape, stride=stride, pad=pad) if need_x else None
58
+ gw = CB.conv2d_grad_w(x.value, g, w.value.shape, stride=stride, pad=pad)
59
+ return [gx, gw]
60
+ return apply_op(lambda a, b: CB.conv2d(a, b, stride=stride, pad=pad), grad_fn, x, w, tape=tape, op_name='conv2d_bf16', bf16_ok=True)
61
+
62
+ def batch_norm2d(x, gamma, beta, running_mean, running_var, momentum=0.1, eps=1e-05, training=True, tape=None):
63
+ from netcl.ops import bf16_act as B
64
+ cache = {}
65
+
66
+ def forward(xt, gt, bt):
67
+ out, mean, var = B.batch_norm2d(xt, gt, bt, running_mean, running_var, momentum=momentum, eps=eps, training=training)
68
+ cache['mean'], cache['var'] = (mean, var)
69
+ return out
70
+
71
+ def grad_fn(g):
72
+ gx, gg, gb = B.batch_norm2d_backward(x.value, gamma.value, _bf16_grad(g), cache['mean'], cache['var'], eps=eps, training=training)
73
+ return [gx, gg, gb]
74
+ return apply_op(forward, grad_fn, x, gamma, beta, tape=tape, op_name='batch_norm2d_bf16', bf16_ok=True)
75
+
76
+ def prelu(x, alpha, tape=None):
77
+ from netcl.ops import bf16_act as B
78
+
79
+ def grad_fn(g):
80
+ gx, ga = B.prelu_backward(x.value, alpha.value, _bf16_grad(g))
81
+ return [gx, ga]
82
+ return apply_op(lambda t, a: B.prelu(t, a), grad_fn, x, alpha, tape=tape, op_name='prelu_bf16', bf16_ok=True)
83
+
84
+ def add(a, b, tape=None):
85
+ from netcl.ops import bf16_act as B
86
+
87
+ def grad_fn(g):
88
+ g = _bf16_grad(g)
89
+ return [g, g]
90
+ return apply_op(lambda x, y: B.add(x, y), grad_fn, a, b, tape=tape, op_name='add_bf16', bf16_ok=True)
91
+
92
+ def upcast_args(args, tape, grad_fn):
93
+ """float32 copies of bf16 activations for an op without a bf16 kernel.
94
+
95
+ Returns ``(args, grad_fn)``. Many grad_fns read their inputs through the
96
+ closure (``x.value``), not through the arguments, so while the wrapped
97
+ grad_fn runs the original nodes show the float32 copy; their bf16 value is
98
+ restored right after."""
99
+ if not any((isinstance(a, Node) and is_bf16(a) for a in args)):
100
+ return (args, grad_fn)
101
+ pairs = []
102
+ new_args = []
103
+ for a in args:
104
+ if isinstance(a, Node) and is_bf16(a):
105
+ c = cast(a, 'float32', tape=tape)
106
+ pairs.append((a, c))
107
+ new_args.append(c)
108
+ else:
109
+ new_args.append(a)
110
+ if grad_fn is None:
111
+ return (tuple(new_args), None)
112
+
113
+ def wrapped(g):
114
+ saved = [(o, o.value) for o, _ in pairs]
115
+ for o, c in pairs:
116
+ o.value = c.value
117
+ try:
118
+ return grad_fn(g)
119
+ finally:
120
+ for o, v in saved:
121
+ o.value = v
122
+ return (tuple(new_args), wrapped)