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.
- netcl/__init__.py +9 -0
- netcl/_legacy_compat.py +41 -0
- netcl/amp.py +133 -0
- netcl/autograd/__init__.py +11 -0
- netcl/autograd/bf16_ops.py +122 -0
- netcl/autograd/compiler.py +469 -0
- netcl/autograd/debug.py +9 -0
- netcl/autograd/engine.py +448 -0
- netcl/autograd/forward_compiler.py +215 -0
- netcl/autograd/graph.py +130 -0
- netcl/autograd/ops.py +2343 -0
- netcl/autograd/shape_ops.py +344 -0
- netcl/autograd/training_compiler.py +166 -0
- netcl/cluster/__init__.py +35 -0
- netcl/cluster/dbscan.py +90 -0
- netcl/cluster/gmm.py +153 -0
- netcl/cluster/kmeans.py +302 -0
- netcl/cluster/metrics.py +223 -0
- netcl/cluster/ops.py +572 -0
- netcl/cluster/spectral.py +148 -0
- netcl/core/__init__.py +7 -0
- netcl/core/autotune.py +184 -0
- netcl/core/backend/__init__.py +40 -0
- netcl/core/backend/base.py +57 -0
- netcl/core/backend/cpu.py +40 -0
- netcl/core/backend/opencl.py +367 -0
- netcl/core/backend/vulkan.py +997 -0
- netcl/core/backend/vulkan_caps.py +59 -0
- netcl/core/backend/vulkan_conv.py +156 -0
- netcl/core/backend/vulkan_gemm.py +571 -0
- netcl/core/backend/vulkan_loss.py +78 -0
- netcl/core/backend/vulkan_norm.py +201 -0
- netcl/core/backend/vulkan_ops.py +1166 -0
- netcl/core/backend/vulkan_spirv.py +1645 -0
- netcl/core/backend/vulkan_spirv_ops.py +2549 -0
- netcl/core/backend/vulkan_winograd.py +317 -0
- netcl/core/bindings/__init__.py +7 -0
- netcl/core/bindings/_ffi.py +129 -0
- netcl/core/bindings/debug.py +42 -0
- netcl/core/bindings/opencl/__init__.py +16 -0
- netcl/core/bindings/opencl/_generated.py +616 -0
- netcl/core/bindings/opencl/_info.py +33 -0
- netcl/core/bindings/opencl/_lib.py +44 -0
- netcl/core/bindings/opencl/api.py +330 -0
- netcl/core/bindings/opencl/errors.py +43 -0
- netcl/core/bindings/opencl/events.py +158 -0
- netcl/core/bindings/opencl/memory.py +203 -0
- netcl/core/bindings/opencl/program.py +378 -0
- netcl/core/bindings/opencl/svm.py +166 -0
- netcl/core/bindings/vulkan/__init__.py +17 -0
- netcl/core/bindings/vulkan/_generated.py +2716 -0
- netcl/core/bindings/vulkan/_lib.py +72 -0
- netcl/core/bindings/vulkan/api.py +122 -0
- netcl/core/bindings/vulkan/errors.py +42 -0
- netcl/core/capabilities.py +269 -0
- netcl/core/device.py +195 -0
- netcl/core/device_profile.py +231 -0
- netcl/core/kernel_selector.py +220 -0
- netcl/core/kernels/__init__.py +5 -0
- netcl/core/kernels/primitives.py +102 -0
- netcl/core/kernels/typed.py +85 -0
- netcl/core/memory.py +649 -0
- netcl/core/parameter.py +74 -0
- netcl/core/precision.py +91 -0
- netcl/core/shape.py +81 -0
- netcl/core/tensor.py +352 -0
- netcl/core/transfer.py +184 -0
- netcl/data/augment.py +37 -0
- netcl/data/augment_gpu.py +111 -0
- netcl/data/dataloader.py +310 -0
- netcl/data/filters.py +79 -0
- netcl/data/gpu_batch.py +77 -0
- netcl/data/shared_batch.py +131 -0
- netcl/distributed/__init__.py +8 -0
- netcl/distributed/collectives.py +123 -0
- netcl/distributed/data_parallel.py +47 -0
- netcl/distributed/device_manager.py +22 -0
- netcl/distributed/trainer.py +45 -0
- netcl/evo/__init__.py +40 -0
- netcl/evo/benchmarks.py +48 -0
- netcl/evo/engine.py +263 -0
- netcl/evo/fitness.py +184 -0
- netcl/evo/genome.py +352 -0
- netcl/evo/ops.py +540 -0
- netcl/evo/population.py +241 -0
- netcl/evo/random.py +73 -0
- netcl/evo/strategies.py +435 -0
- netcl/io/__init__.py +25 -0
- netcl/io/checkpoint.py +61 -0
- netcl/io/interop.py +385 -0
- netcl/io/onnx_export.py +139 -0
- netcl/io/serialization.py +101 -0
- netcl/nn/__init__.py +39 -0
- netcl/nn/batchnorm.py +441 -0
- netcl/nn/containers.py +492 -0
- netcl/nn/decorators.py +37 -0
- netcl/nn/factory.py +151 -0
- netcl/nn/functional.py +142 -0
- netcl/nn/groupnorm.py +132 -0
- netcl/nn/init.py +74 -0
- netcl/nn/layernorm.py +96 -0
- netcl/nn/layers.py +970 -0
- netcl/nn/loss.py +72 -0
- netcl/nn/margin.py +268 -0
- netcl/nn/modern.py +309 -0
- netcl/nn/modules.py +75 -0
- netcl/nn/padding.py +122 -0
- netcl/nn/pooling.py +344 -0
- netcl/nn/residual.py +19 -0
- netcl/nn/resnet.py +151 -0
- netcl/nn/simple.py +30 -0
- netcl/nn/state.py +282 -0
- netcl/nn/transformer.py +168 -0
- netcl/ops/__init__.py +15 -0
- netcl/ops/attention.py +151 -0
- netcl/ops/bf16_act.py +131 -0
- netcl/ops/bmm.py +85 -0
- netcl/ops/broadcast.py +75 -0
- netcl/ops/conv2d.py +1056 -0
- netcl/ops/conv2d_cpu.py +176 -0
- netcl/ops/conv2d_dilated.py +287 -0
- netcl/ops/conv2d_optimized.py +514 -0
- netcl/ops/conv2d_planner.py +1210 -0
- netcl/ops/conv2d_pointwise.py +249 -0
- netcl/ops/conv_bf16.py +208 -0
- netcl/ops/conv_transpose2d.py +112 -0
- netcl/ops/depthwise_conv2d.py +213 -0
- netcl/ops/elementwise.py +1006 -0
- netcl/ops/elementwise_optimized.py +167 -0
- netcl/ops/fused_ops.py +150 -0
- netcl/ops/grid_sample.py +236 -0
- netcl/ops/im2col.py +153 -0
- netcl/ops/indexing.py +169 -0
- netcl/ops/jit_fusion.py +176 -0
- netcl/ops/lm_ops.py +150 -0
- netcl/ops/matmul.py +411 -0
- netcl/ops/matmul_optimized.py +457 -0
- netcl/ops/norm_rope.py +113 -0
- netcl/ops/permute.py +87 -0
- netcl/ops/reduction.py +125 -0
- netcl/ops/softmax.py +175 -0
- netcl/ops/softmax_fp16.py +22 -0
- netcl/ops/softmax_fused.py +79 -0
- netcl/ops/tc_gemm.py +200 -0
- netcl/ops/tensor_ops.py +313 -0
- netcl/ops/transpose.py +60 -0
- netcl/ops/upsample.py +178 -0
- netcl/ops/winograd_bf16.py +100 -0
- netcl/ops/winograd_fused.py +75 -0
- netcl/optim/__init__.py +11 -0
- netcl/optim/_utils.py +6 -0
- netcl/optim/adam.py +137 -0
- netcl/optim/adamw.py +572 -0
- netcl/optim/amp.py +42 -0
- netcl/optim/clip.py +116 -0
- netcl/optim/ema.py +131 -0
- netcl/optim/lr_plateau.py +68 -0
- netcl/optim/lr_scheduler.py +14 -0
- netcl/optim/momentum.py +41 -0
- netcl/optim/rmsprop.py +59 -0
- netcl/optim/sgd.py +158 -0
- netcl/profiling/__init__.py +5 -0
- netcl/profiling/autotuner.py +335 -0
- netcl/profiling/timing.py +23 -0
- netcl/runtime/__init__.py +7 -0
- netcl/runtime/cache.py +44 -0
- netcl/runtime/capture.py +257 -0
- netcl/runtime/graph.py +117 -0
- netcl/runtime/graph_fusion.py +277 -0
- netcl/runtime/perf.py +21 -0
- netcl/runtime/scheduler.py +47 -0
- netcl/ssl/__init__.py +44 -0
- netcl/ssl/deep_cluster.py +261 -0
- netcl/ssl/evaluate.py +154 -0
- netcl/ssl/heads.py +190 -0
- netcl/ssl/losses.py +242 -0
- netcl/ssl/methods.py +338 -0
- netcl/ssl/views.py +312 -0
- netcl/text/__init__.py +4 -0
- netcl/text/bpe.py +170 -0
- netcl/text/chat.py +103 -0
- netcl/trainer/__init__.py +2 -0
- netcl/trainer/trainer.py +282 -0
- netcl/utils/__init__.py +3 -0
- netcl/utils/data.py +22 -0
- netcl/utils/progress.py +92 -0
- netcl_py36-0.6.1.dist-info/METADATA +167 -0
- netcl_py36-0.6.1.dist-info/RECORD +190 -0
- netcl_py36-0.6.1.dist-info/WHEEL +5 -0
- 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']
|
netcl/_legacy_compat.py
ADDED
|
@@ -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)
|