nablaengine 1.0.2__py3-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.
- nablaengine/__init__.py +4 -0
- nablaengine/_fixtures/README.md +19 -0
- nablaengine/_fixtures/data/mf_s0.npz +0 -0
- nablaengine/_fixtures/mjlab/LICENSE +27 -0
- nablaengine/_fixtures/mjlab/README.md +113 -0
- nablaengine/_fixtures/mjlab/g1_meta.json +32 -0
- nablaengine/_fixtures/mjlab/g1_train.mjb +0 -0
- nablaengine/_optional.py +30 -0
- nablaengine/_paths.py +38 -0
- nablaengine/actuators/__init__.py +169 -0
- nablaengine/actuators/bam.py +306 -0
- nablaengine/actuators/bam_params/LICENSE +202 -0
- nablaengine/actuators/bam_params/xl330/m6.json +19 -0
- nablaengine/boxbox.py +259 -0
- nablaengine/ccd.py +1122 -0
- nablaengine/checks.py +376 -0
- nablaengine/cuda.py +483 -0
- nablaengine/dist_query.py +628 -0
- nablaengine/dual.py +223 -0
- nablaengine/dyn_query.py +685 -0
- nablaengine/engines.py +114 -0
- nablaengine/envs/__init__.py +24 -0
- nablaengine/envs/brax.py +165 -0
- nablaengine/envs/convert.py +771 -0
- nablaengine/envs/dmc.py +523 -0
- nablaengine/envs/env.py +233 -0
- nablaengine/envs/kin.py +371 -0
- nablaengine/envs/ops.py +134 -0
- nablaengine/envs/rewards.py +57 -0
- nablaengine/fixtures.py +243 -0
- nablaengine/forest_engine/__init__.py +0 -0
- nablaengine/forest_engine/adjoint.py +1726 -0
- nablaengine/forest_engine/adjoint_contact.py +493 -0
- nablaengine/forest_engine/bam_hooks.py +248 -0
- nablaengine/forest_engine/body_params.py +1007 -0
- nablaengine/forest_engine/capacity_diag.py +116 -0
- nablaengine/forest_engine/ccd_coop.py +250 -0
- nablaengine/forest_engine/chol_blk.py +80 -0
- nablaengine/forest_engine/contact_forces.py +142 -0
- nablaengine/forest_engine/contact_vjp.py +462 -0
- nablaengine/forest_engine/convex.py +1331 -0
- nablaengine/forest_engine/cylinder.py +73 -0
- nablaengine/forest_engine/dist_device.py +923 -0
- nablaengine/forest_engine/dyn_device.py +696 -0
- nablaengine/forest_engine/ellipsoid.py +179 -0
- nablaengine/forest_engine/elliptic.py +272 -0
- nablaengine/forest_engine/equality.py +842 -0
- nablaengine/forest_engine/floss.py +148 -0
- nablaengine/forest_engine/foot_offset.py +368 -0
- nablaengine/forest_engine/free_gyro.py +288 -0
- nablaengine/forest_engine/host.py +530 -0
- nablaengine/forest_engine/kdof64.py +127 -0
- nablaengine/forest_engine/kinematics.py +320 -0
- nablaengine/forest_engine/margin.py +167 -0
- nablaengine/forest_engine/margin_convex.py +326 -0
- nablaengine/forest_engine/midphase.py +439 -0
- nablaengine/forest_engine/model_hooks.py +913 -0
- nablaengine/forest_engine/motor_hooks.py +50 -0
- nablaengine/forest_engine/muscle.py +485 -0
- nablaengine/forest_engine/nb128.py +118 -0
- nablaengine/forest_engine/nb64.py +163 -0
- nablaengine/forest_engine/noslip.py +1124 -0
- nablaengine/forest_engine/nv128.py +1944 -0
- nablaengine/forest_engine/object_size.py +283 -0
- nablaengine/forest_engine/replay_guard.py +40 -0
- nablaengine/forest_engine/root_spread.py +126 -0
- nablaengine/forest_engine/solref.py +74 -0
- nablaengine/forest_engine/source.py +1464 -0
- nablaengine/forest_engine/sparse_pattern.py +527 -0
- nablaengine/forest_engine/spatial.py +1045 -0
- nablaengine/forest_engine/step.py +3083 -0
- nablaengine/forest_engine/surrogate.py +498 -0
- nablaengine/forest_engine/tape.py +199 -0
- nablaengine/forest_engine/tendon.py +845 -0
- nablaengine/forest_engine/terrain.py +1059 -0
- nablaengine/forest_engine/world_forces.py +166 -0
- nablaengine/forest_engine/world_params.py +230 -0
- nablaengine/g1_engine/__init__.py +0 -0
- nablaengine/g1_engine/adjoint.py +1661 -0
- nablaengine/g1_engine/adjoint_contact.py +577 -0
- nablaengine/g1_engine/bam_hooks.py +596 -0
- nablaengine/g1_engine/condim4.py +245 -0
- nablaengine/g1_engine/contact_forces.py +500 -0
- nablaengine/g1_engine/cylccd.py +1158 -0
- nablaengine/g1_engine/cylinder.py +216 -0
- nablaengine/g1_engine/elliptic.py +565 -0
- nablaengine/g1_engine/exact_replay.py +61 -0
- nablaengine/g1_engine/host.py +358 -0
- nablaengine/g1_engine/kinematics.py +320 -0
- nablaengine/g1_engine/mesh.py +305 -0
- nablaengine/g1_engine/mesh_tables.py +79 -0
- nablaengine/g1_engine/model_hooks.py +919 -0
- nablaengine/g1_engine/motor_hooks.py +70 -0
- nablaengine/g1_engine/replay_guard.py +55 -0
- nablaengine/g1_engine/source.py +1107 -0
- nablaengine/g1_engine/sphbox.py +93 -0
- nablaengine/g1_engine/step.py +3716 -0
- nablaengine/g1_engine/tape.py +173 -0
- nablaengine/g1_engine/world_params.py +447 -0
- nablaengine/identity.py +401 -0
- nablaengine/jax_ffi.py +2536 -0
- nablaengine/model/__init__.py +1 -0
- nablaengine/model/capability.py +694 -0
- nablaengine/model/fields.py +317 -0
- nablaengine/model/gravcomp.py +64 -0
- nablaengine/model/invweight.py +145 -0
- nablaengine/motor.py +143 -0
- nablaengine/object_geometry.py +609 -0
- nablaengine/params.py +258 -0
- nablaengine/provenance.py +196 -0
- nablaengine/reference/__init__.py +0 -0
- nablaengine/reference/adjoint_groups.py +226 -0
- nablaengine/reference/jax64.py +690 -0
- nablaengine/reference/warp_physics.py +262 -0
- nablaengine/sensors/__init__.py +4 -0
- nablaengine/sensors/cameras.py +285 -0
- nablaengine/sensors/data/LIVOX_MID360_LICENSE +21 -0
- nablaengine/sensors/data/livox_mid360.npz +0 -0
- nablaengine/sensors/g1.py +521 -0
- nablaengine/sensors/jax_rays.py +364 -0
- nablaengine/sensors/optix_rays.py +725 -0
- nablaengine/sensors/raycore.py +630 -0
- nablaengine/sensors/raygrad.py +374 -0
- nablaengine/sensors/raygrad_cuda.py +191 -0
- nablaengine/sensors/robot_mesh.py +273 -0
- nablaengine/sensors/torch_rays.py +275 -0
- nablaengine/terrain.py +424 -0
- nablaengine/torch_ffi.py +1328 -0
- nablaengine/workdir.py +37 -0
- nablaengine-1.0.2.dist-info/METADATA +236 -0
- nablaengine-1.0.2.dist-info/RECORD +136 -0
- nablaengine-1.0.2.dist-info/WHEEL +5 -0
- nablaengine-1.0.2.dist-info/licenses/LICENSE +202 -0
- nablaengine-1.0.2.dist-info/licenses/NOTICE +23 -0
- nablaengine-1.0.2.dist-info/licenses/THIRD_PARTY_NOTICES.md +176 -0
- nablaengine-1.0.2.dist-info/top_level.txt +1 -0
nablaengine/checks.py
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
"""Shared code of the verification scripts: the adjoint check binary (the forward kernel k_substep, the tape and the
|
|
2
|
+
analytic adjoint k_adjoint with a small host program) and the digest manifest of the forward outputs."""
|
|
3
|
+
|
|
4
|
+
import datetime
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import subprocess
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from nablaengine import cuda, provenance
|
|
14
|
+
from nablaengine.cuda import compile_cuda
|
|
15
|
+
from nablaengine.g1_engine import adjoint, step, tape
|
|
16
|
+
from nablaengine.g1_engine.host import KERNEL, loader
|
|
17
|
+
|
|
18
|
+
CHECKOUT = Path(__file__).resolve().parents[2]
|
|
19
|
+
DIGESTS = CHECKOUT / "fixtures" / "mjlab" / "engine_digests.json"
|
|
20
|
+
DIGESTS_ENV = "DK_DIGESTS"
|
|
21
|
+
DIGESTS_FORMAT = "dk-engine-digests/1"
|
|
22
|
+
|
|
23
|
+
HOST = r"""
|
|
24
|
+
#include <cstdio>
|
|
25
|
+
#include <cstdlib>
|
|
26
|
+
#include <vector>
|
|
27
|
+
static std::vector<float> readf(const char* path, size_t n) {
|
|
28
|
+
std::vector<float> v(n);
|
|
29
|
+
FILE* f = fopen(path, "rb");
|
|
30
|
+
if (!f || fread(v.data(), 4, n, f) != n) { fprintf(stderr, "read %s\n", path); exit(1); }
|
|
31
|
+
fclose(f);
|
|
32
|
+
return v;
|
|
33
|
+
}
|
|
34
|
+
template <class T> static void writef(const char* path, const T* v, size_t n) { FILE* f = fopen(path, "wb"); fwrite(v, sizeof(T), n, f); fclose(f); }
|
|
35
|
+
static float* up(const std::vector<float>& h) { float* d; cudaMalloc(&d, h.size() * 4); cudaMemcpy(d, h.data(), h.size() * 4, cudaMemcpyHostToDevice); return d; }
|
|
36
|
+
template <class T> static void down(const char* dir, const char* name, const T* d, size_t n) {
|
|
37
|
+
std::vector<T> h(n);
|
|
38
|
+
cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost);
|
|
39
|
+
char path[1024];
|
|
40
|
+
snprintf(path, sizeof path, "%s/%s", dir, name);
|
|
41
|
+
writef(path, h.data(), n);
|
|
42
|
+
}
|
|
43
|
+
int main(int argc, char** argv) { // dir nworld iterations substeps ncot reps debug [worlds per SM [carveout [delta]]]
|
|
44
|
+
const char* dir = argv[1];
|
|
45
|
+
int nw = atoi(argv[2]), iters = atoi(argv[3]), nsub = atoi(argv[4]), ncot = atoi(argv[5]), reps = atoi(argv[6]);
|
|
46
|
+
bool dbg_on = atoi(argv[7]) > 0;
|
|
47
|
+
// k_adjoint's launch (adjoint.py adj_launch_smem): the production choice for this GPU (-1), or at most argv[8] > 0
|
|
48
|
+
// worlds per SM (more shared memory than it needs); 0 is a failure
|
|
49
|
+
cudaError_t err_a;
|
|
50
|
+
const size_t smem_a = adj_launch_smem(argc > 8 && atoi(argv[8]) > 0 ? atoi(argv[8]) : -1, &err_a);
|
|
51
|
+
if (!smem_a) { fprintf(stderr, "adj_launch_smem: %s\n", cudaGetErrorString(err_a)); return 1; }
|
|
52
|
+
char path[1024], name[256];
|
|
53
|
+
snprintf(path, sizeof path, "%s/consts.bin", dir);
|
|
54
|
+
std::vector<float> cf = readf(path, NCONST);
|
|
55
|
+
const float* p = cf.data();
|
|
56
|
+
LOAD_CONSTS
|
|
57
|
+
#define IN(name, n) snprintf(path, sizeof path, "%s/" #name ".bin", dir); float* d_##name = up(readf(path, (size_t)nw * (n)));
|
|
58
|
+
IN(qpos, NQ) IN(qvel, NV) IN(warm, NV) IN(ctrl, NV - 6) IN(fric, 1) IN(com, 3)
|
|
59
|
+
#if DK_ADJ_CLAMP_KV == 2
|
|
60
|
+
// the soft clamp (adjoint.py): its delta (argv[10], default 0: the gradients of DK_ADJ_CLAMP_KV=1) and the ctrl the
|
|
61
|
+
// adjoint then always needs
|
|
62
|
+
const float clamp_soft = argc > 10 ? (float)atof(argv[10]) : 0.f;
|
|
63
|
+
#define ADJ_CTRL(on) d_ctrl
|
|
64
|
+
#else
|
|
65
|
+
#define ADJ_CTRL(on) ((on) ? d_ctrl : nullptr)
|
|
66
|
+
#endif
|
|
67
|
+
float *oq, *ov, *ow, *oc, *tp; int* oi;
|
|
68
|
+
cudaMalloc(&oc, (size_t)nw * MAXCON * 8 * 4);
|
|
69
|
+
cudaMalloc(&oq, (size_t)nw * NQ * 4); cudaMalloc(&ov, (size_t)nw * NV * 4); cudaMalloc(&ow, (size_t)nw * NV * 4);
|
|
70
|
+
cudaMalloc(&oi, (size_t)nw * 16);
|
|
71
|
+
size_t ntape = (size_t)nw * nsub * REC_WORDS;
|
|
72
|
+
cudaMalloc(&tp, ntape * 4);
|
|
73
|
+
cudaFuncSetAttribute(k_substep, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)sizeof(Sim));
|
|
74
|
+
if (argc > 9 && atoi(argv[9]) >= 0) // shared-memory carveout preference of k_adjoint, percent (the rest is L1)
|
|
75
|
+
cudaFuncSetAttribute(k_adjoint, cudaFuncAttributePreferredSharedMemoryCarveout, atoi(argv[9]));
|
|
76
|
+
int nblk_f = 0, nblk_a = 0;
|
|
77
|
+
cudaOccupancyMaxActiveBlocksPerMultiprocessor(&nblk_f, k_substep, 32, sizeof(Sim));
|
|
78
|
+
cudaOccupancyMaxActiveBlocksPerMultiprocessor(&nblk_a, k_adjoint, 32, smem_a);
|
|
79
|
+
int nprof_f = 0, nprof_a = 0; // launches since g_prof / g_aprof were zeroed (-DDK_PROFILE: printed with them)
|
|
80
|
+
auto fwd = [&]() {
|
|
81
|
+
k_substep<<<nw, 32, sizeof(Sim)>>>(nw, d_qpos, d_qvel, d_warm, d_ctrl, d_fric, d_com, iters, nsub, oq, ov, ow, oi, oc, tp);
|
|
82
|
+
nprof_f++;
|
|
83
|
+
};
|
|
84
|
+
#ifdef DK_PROFILE
|
|
85
|
+
// g_prof and g_aprof sum over every launch since they were last zeroed: each is zeroed before the launch it profiles
|
|
86
|
+
// (the first forward, the first adjoint) and read right after, with the launches since printed (run() requires 1:
|
|
87
|
+
// a reading moved after the timing loop would sum over its launches)
|
|
88
|
+
static const unsigned long long prof_zero[NPROF > NAPROF ? NPROF : NAPROF] = {};
|
|
89
|
+
cudaMemcpyToSymbol(g_prof, prof_zero, sizeof(unsigned long long) * NPROF);
|
|
90
|
+
nprof_f = 0;
|
|
91
|
+
#endif
|
|
92
|
+
fwd();
|
|
93
|
+
cudaDeviceSynchronize();
|
|
94
|
+
if (const char* tin = getenv("DK_TAPE_IN")) { // the adjoint on another binary's tape (run(): the forward unit's build, as on sm_120)
|
|
95
|
+
std::vector<float> ht = readf(tin, ntape);
|
|
96
|
+
cudaMemcpy(tp, ht.data(), ntape * 4, cudaMemcpyHostToDevice);
|
|
97
|
+
}
|
|
98
|
+
down(dir, "out_qpos.bin", oq, (size_t)nw * NQ); down(dir, "out_qvel.bin", ov, (size_t)nw * NV);
|
|
99
|
+
down(dir, "out_warm.bin", ow, (size_t)nw * NV); down(dir, "out_info.bin", oi, (size_t)nw * 4);
|
|
100
|
+
down(dir, "out_con.bin", oc, (size_t)nw * MAXCON * 8);
|
|
101
|
+
down(dir, "tape.bin", tp, ntape);
|
|
102
|
+
float *gq, *gv, *gu, *dbg = nullptr; int* ai;
|
|
103
|
+
cudaMalloc(&gq, (size_t)nw * NQ * 4); cudaMalloc(&gv, (size_t)nw * NV * 4); cudaMalloc(&gu, (size_t)nw * (NV - 6) * 4);
|
|
104
|
+
cudaMalloc(&ai, (size_t)nw * 4);
|
|
105
|
+
size_t ndbg = (size_t)nw * nsub * DBG_WORDS;
|
|
106
|
+
if (dbg_on) cudaMalloc(&dbg, ndbg * 4);
|
|
107
|
+
float *cq = nullptr, *cv = nullptr;
|
|
108
|
+
for (int c = 0; c < ncot; c++) {
|
|
109
|
+
snprintf(path, sizeof path, "%s/cot%d_qpos.bin", dir, c);
|
|
110
|
+
std::vector<float> hq = readf(path, (size_t)nw * NQ);
|
|
111
|
+
snprintf(path, sizeof path, "%s/cot%d_qvel.bin", dir, c);
|
|
112
|
+
std::vector<float> hv = readf(path, (size_t)nw * NV);
|
|
113
|
+
if (cq) { cudaFree(cq); cudaFree(cv); }
|
|
114
|
+
cq = up(hq); cv = up(hv);
|
|
115
|
+
if (dbg) cudaMemset(dbg, 0, ndbg * 4);
|
|
116
|
+
#ifdef DK_PROFILE
|
|
117
|
+
if (c == 0) { cudaMemcpyToSymbol(g_aprof, prof_zero, sizeof(unsigned long long) * NAPROF); nprof_a = 0; }
|
|
118
|
+
#endif
|
|
119
|
+
k_adjoint<<<nw, 32, smem_a>>>(nw, nsub, tp, d_fric, d_com, cq, cv, gq, gv, gu, ai, dbg, ADJ_CTRL(dbg)
|
|
120
|
+
ADJ_SOFT_ARG(clamp_soft));
|
|
121
|
+
nprof_a++;
|
|
122
|
+
cudaDeviceSynchronize();
|
|
123
|
+
#ifdef DK_PROFILE
|
|
124
|
+
if (c == 0) { // -DDK_PROFILE: the phase cycles of the first forward launch and of this first adjoint launch
|
|
125
|
+
unsigned long long hp[NPROF], ha[NAPROF];
|
|
126
|
+
cudaMemcpyFromSymbol(hp, g_prof, sizeof hp);
|
|
127
|
+
cudaMemcpyFromSymbol(ha, g_aprof, sizeof ha);
|
|
128
|
+
printf("{\"prof_launches\": %d, \"adj_prof_launches\": %d, \"prof_cycles\": [", nprof_f, nprof_a);
|
|
129
|
+
for (int k = 0; k < NPROF; k++) printf("%s%llu", k ? ", " : "", hp[k]);
|
|
130
|
+
printf("], \"adj_prof_cycles\": [");
|
|
131
|
+
for (int k = 0; k < NAPROF; k++) printf("%s%llu", k ? ", " : "", ha[k]);
|
|
132
|
+
printf("]}\n");
|
|
133
|
+
}
|
|
134
|
+
#endif
|
|
135
|
+
snprintf(name, sizeof name, "grad%d_qpos.bin", c); down(dir, name, gq, (size_t)nw * NQ);
|
|
136
|
+
snprintf(name, sizeof name, "grad%d_qvel.bin", c); down(dir, name, gv, (size_t)nw * NV);
|
|
137
|
+
snprintf(name, sizeof name, "grad%d_ctrl.bin", c); down(dir, name, gu, (size_t)nw * (NV - 6));
|
|
138
|
+
snprintf(name, sizeof name, "adj_info%d.bin", c); down(dir, name, ai, (size_t)nw);
|
|
139
|
+
if (dbg && c == 0) down(dir, "dbg0.bin", dbg, ndbg); // the intermediates of cotangent 0 (as the dump's)
|
|
140
|
+
}
|
|
141
|
+
float ms_f = 0.f, ms_a = 0.f;
|
|
142
|
+
if (reps > 0) { // forward with the tape, then the adjoint (cotangent ncot - 1; debug output off), after warm-up launches
|
|
143
|
+
cudaEvent_t e0, e1; cudaEventCreate(&e0); cudaEventCreate(&e1);
|
|
144
|
+
for (int i = 0; i < 3; i++) fwd();
|
|
145
|
+
cudaEventRecord(e0);
|
|
146
|
+
for (int i = 0; i < reps; i++) fwd();
|
|
147
|
+
cudaEventRecord(e1); cudaEventSynchronize(e1);
|
|
148
|
+
cudaEventElapsedTime(&ms_f, e0, e1);
|
|
149
|
+
auto adj = [&]() {
|
|
150
|
+
k_adjoint<<<nw, 32, smem_a>>>(nw, nsub, tp, d_fric, d_com, cq, cv, gq, gv, gu, ai, nullptr, ADJ_CTRL(false)
|
|
151
|
+
ADJ_SOFT_ARG(clamp_soft));
|
|
152
|
+
nprof_a++;
|
|
153
|
+
};
|
|
154
|
+
for (int i = 0; i < 3; i++) adj();
|
|
155
|
+
cudaEventRecord(e0);
|
|
156
|
+
for (int i = 0; i < reps; i++) adj();
|
|
157
|
+
cudaEventRecord(e1); cudaEventSynchronize(e1);
|
|
158
|
+
cudaEventElapsedTime(&ms_a, e0, e1);
|
|
159
|
+
ms_f /= reps; ms_a /= reps;
|
|
160
|
+
}
|
|
161
|
+
printf("{\"nworld\": %d, \"ms_forward_tape\": %.5f, \"ms_adjoint\": %.5f, \"err\": \"%s\", \"sizeof_sim\": %zu, "
|
|
162
|
+
"\"sizeof_adj\": %zu, \"blocks_per_sm_forward\": %d, \"blocks_per_sm_adjoint\": %d}\n", nw, ms_f, ms_a,
|
|
163
|
+
cudaGetErrorString(cudaGetLastError()), sizeof(Sim), sizeof(Adj), nblk_f, nblk_a);
|
|
164
|
+
return 0;
|
|
165
|
+
}
|
|
166
|
+
"""
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
FORWARD_OF = {}
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def binary_source(m, mt):
|
|
173
|
+
"""(CUDA source, packed constants) of build()'s binary for model m (the forward and adjoint device code,
|
|
174
|
+
nablaengine.g1_engine.host's KERNEL and HOST's main; scripts/identity_gate.py hashes it)."""
|
|
175
|
+
consts, lays, sizes = adjoint.engine_constants(m, mt["foot_pairs"])
|
|
176
|
+
src = (adjoint.cuda_source(m) + KERNEL
|
|
177
|
+
+ HOST.replace("LOAD_CONSTS", loader(lays, sizes)).replace("NCONST", str(len(consts))))
|
|
178
|
+
return src, consts
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def binary_builds(target=None):
|
|
182
|
+
"""build()'s compilations of one source for build target target (default cuda.arch()): [(file suffix, unit of
|
|
183
|
+
cuda.compile_cuda)]: one as the forward unit where the forward / kinematics unit has the adjoint units' flags,
|
|
184
|
+
else [("", None), ("_fwd", "forward")] (run() takes the forward and tape from the _fwd binary)."""
|
|
185
|
+
split = cuda.arch_flags("forward", target) != cuda.arch_flags(None, target)
|
|
186
|
+
return [("", None), ("_fwd", "forward")] if split else [("", "forward")]
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def build(m, mt, work, tag, defines, flags=()):
|
|
190
|
+
"""Compile the forward + adjoint binary with the -D definitions (and extra nvcc flags); returns its path. Where the
|
|
191
|
+
forward / kinematics unit has other architecture flags than the adjoint units (nablaengine.cuda.arch_flags: NVVM 7
|
|
192
|
+
on sm_120), the same source is also built with the forward unit's flags (<tag>_fwd, FORWARD_OF): run() takes the
|
|
193
|
+
forward outputs and the tape from it and runs this binary's k_adjoint on that tape, as the FFI library does. The
|
|
194
|
+
binary that runs the forward (this one where the flags are the same, else <tag>_fwd) is compiled as the forward
|
|
195
|
+
unit, so it also gets the target's forward-unit -D options (nablaengine.cuda.unit_defines: the register caps on
|
|
196
|
+
sm_90), as the FFI library's unit with the forward kernels."""
|
|
197
|
+
src, consts = binary_source(m, mt)
|
|
198
|
+
extra = [f"-D{d}" for d in defines] + list(flags)
|
|
199
|
+
adj_caps = cuda.adjoint_defines(None, extra)
|
|
200
|
+
adj_caps += cuda.tree_adj_cap_defines(None, extra + adj_caps)
|
|
201
|
+
extra += cuda.capbox_coop_defines(None, src, extra)
|
|
202
|
+
(work / f"{tag}.cu").write_text(adjoint.with_adj_bounds(src) if adj_caps else src)
|
|
203
|
+
consts.tofile(work / "consts.bin")
|
|
204
|
+
for suffix, unit in binary_builds():
|
|
205
|
+
ex = extra + (adj_caps if not suffix else [])
|
|
206
|
+
compile_cuda(work / f"{tag}.cu", work / f"{tag}{suffix}", ex, unit=unit)
|
|
207
|
+
if suffix:
|
|
208
|
+
FORWARD_OF[work / tag] = work / f"{tag}{suffix}"
|
|
209
|
+
return work / tag
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def run(binary, work, m, nw, iterations, nsub, ncot, reps, debug, timeout, blocks_per_sm=0, carveout=-1,
|
|
213
|
+
clamp_soft=None, tape_in=None):
|
|
214
|
+
"""One run: (its JSON line, outputs: tape (nw, nsub, REC_WORDS), info, con (the last substep's contacts), qpos, qvel,
|
|
215
|
+
grad{c}_*, adj_info{c}, and with debug the decoded records of cotangent 0, dbg0). blocks_per_sm > 0 caps the adjoint's
|
|
216
|
+
worlds per SM (it requests more shared memory than it needs), 0 is the production launch (adjoint.py
|
|
217
|
+
adj_launch_smem: on V100 at most 4 of the 6 worlds that fit an SM); carveout >= 0 sets the adjoint's preferred
|
|
218
|
+
shared-memory carveout (percent of the SM's shared memory, the rest is L1).
|
|
219
|
+
clamp_soft: the soft clamp's delta of a DK_ADJ_CLAMP_KV=2 build (float32; the others ignore it; default 0).
|
|
220
|
+
tape_in: a tape file (float32, nw * nsub records) the adjoint runs on instead of the binary's own forward's (which
|
|
221
|
+
still runs: info, con, qpos, qvel are its own; the returned tape is tape_in's). Without tape_in, a binary with a
|
|
222
|
+
forward-unit build (FORWARD_OF) runs on that build's tape, and the forward outputs (the files in work too) and
|
|
223
|
+
ms_forward_tape are that build's."""
|
|
224
|
+
fwd = FORWARD_OF.get(Path(binary))
|
|
225
|
+
if fwd is not None and tape_in is None:
|
|
226
|
+
rf, fo = run(fwd, work, m, nw, iterations, nsub, min(ncot, 1) if reps else 0, reps, False, timeout,
|
|
227
|
+
clamp_soft=clamp_soft)
|
|
228
|
+
names = ("out_qpos.bin", "out_qvel.bin", "out_warm.bin", "out_info.bin", "out_con.bin")
|
|
229
|
+
keep = {n: (work / n).read_bytes() for n in names}
|
|
230
|
+
tin = work / f"{Path(binary).name}_tape_in.bin"
|
|
231
|
+
os.replace(work / "tape.bin", tin)
|
|
232
|
+
try:
|
|
233
|
+
r, out = run(binary, work, m, nw, iterations, nsub, ncot, reps, debug, timeout, blocks_per_sm, carveout,
|
|
234
|
+
clamp_soft, tape_in=tin)
|
|
235
|
+
finally:
|
|
236
|
+
tin.unlink(missing_ok=True)
|
|
237
|
+
for n, b in keep.items():
|
|
238
|
+
(work / n).write_bytes(b)
|
|
239
|
+
out.update({k: fo[k] for k in ("info", "con", "qpos", "qvel")})
|
|
240
|
+
r.update(ms_forward_tape=rf["ms_forward_tape"], blocks_per_sm_forward=rf["blocks_per_sm_forward"],
|
|
241
|
+
forward_build=Path(fwd).name)
|
|
242
|
+
return r, out
|
|
243
|
+
soft = [] if clamp_soft is None else [repr(float(np.float32(clamp_soft)))]
|
|
244
|
+
env = dict(os.environ, DK_TAPE_IN=str(tape_in)) if tape_in is not None else None
|
|
245
|
+
o = subprocess.run([str(binary), str(work), str(nw), str(iterations), str(nsub), str(ncot), str(reps),
|
|
246
|
+
str(int(debug)), str(int(blocks_per_sm)), str(int(carveout))] + soft, check=True,
|
|
247
|
+
timeout=timeout, stdout=subprocess.PIPE, universal_newlines=True, env=env).stdout
|
|
248
|
+
r = json.loads(next(line for line in o.splitlines() if line.startswith('{"nworld"')))
|
|
249
|
+
if r["err"] != "no error":
|
|
250
|
+
raise RuntimeError(f"CUDA error: {r['err']}")
|
|
251
|
+
prof = [json.loads(line) for line in o.splitlines() if line.startswith('{"prof_launches"')]
|
|
252
|
+
if prof:
|
|
253
|
+
if (prof[0]["prof_launches"], prof[0]["adj_prof_launches"]) != (1, 1):
|
|
254
|
+
raise RuntimeError(f"profile counters summed over several launches: {prof[0]['prof_launches']} forward, "
|
|
255
|
+
f"{prof[0]['adj_prof_launches']} adjoint")
|
|
256
|
+
r.update(prof[0])
|
|
257
|
+
f = lambda name, dt=np.float32: np.fromfile(work / name, dt)
|
|
258
|
+
out = dict(tape=f("tape.bin").reshape(nw, nsub, tape.rec_words(m)), info=f("out_info.bin", np.int32).reshape(nw, 4),
|
|
259
|
+
qpos=f("out_qpos.bin").reshape(nw, m.nq), qvel=f("out_qvel.bin").reshape(nw, m.nv),
|
|
260
|
+
con=f("out_con.bin").reshape(nw, step.maxcon(m), 8))
|
|
261
|
+
for c in range(ncot):
|
|
262
|
+
out[f"grad{c}_qpos"] = f(f"grad{c}_qpos.bin").reshape(nw, m.nq)
|
|
263
|
+
out[f"grad{c}_qvel"] = f(f"grad{c}_qvel.bin").reshape(nw, m.nv)
|
|
264
|
+
out[f"grad{c}_ctrl"] = f(f"grad{c}_ctrl.bin").reshape(nw, m.nu)
|
|
265
|
+
out[f"adj_info{c}"] = f(f"adj_info{c}.bin", np.int32)
|
|
266
|
+
if debug and c == 0:
|
|
267
|
+
out["dbg0"] = adjoint.decode_debug(f("dbg0.bin").reshape(nw, nsub, -1), m)
|
|
268
|
+
return r, out
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def write_inputs(work, arrs):
|
|
272
|
+
for k, a in arrs.items():
|
|
273
|
+
np.ascontiguousarray(a, np.float32).tofile(work / f"{k}.bin")
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def corpus_inputs(z, q=None):
|
|
277
|
+
"""The binary's input arrays from a corpus (qpos replaced by q when given), with its three cotangents."""
|
|
278
|
+
arrs = dict(qpos=z["qpos"] if q is None else q, qvel=z["qvel"], warm=z["qacc_warmstart"], ctrl=z["ctrl"],
|
|
279
|
+
fric=z["friction"], com=z["com"])
|
|
280
|
+
for c in range(3):
|
|
281
|
+
arrs[f"cot{c}_qpos"], arrs[f"cot{c}_qvel"] = z[f"cot{c}_qpos"], z[f"cot{c}_qvel"]
|
|
282
|
+
return arrs
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def array_digest(a):
|
|
287
|
+
"""{shape, dtype, sha256} of an array (sha256 of its C-order bytes)."""
|
|
288
|
+
a = np.ascontiguousarray(a)
|
|
289
|
+
return dict(shape=list(a.shape), dtype=a.dtype.str, sha256=hashlib.sha256(a.tobytes()).hexdigest())
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def inputs_digest(arrays, names=("qpos", "qvel", "warm", "ctrl", "fric", "com")):
|
|
293
|
+
"""sha256 of the float32 inputs as the binaries read them, each preceded by its name."""
|
|
294
|
+
h = hashlib.sha256()
|
|
295
|
+
for k in names:
|
|
296
|
+
h.update(k.encode())
|
|
297
|
+
h.update(np.ascontiguousarray(arrays[k], np.float32).tobytes())
|
|
298
|
+
return h.hexdigest()
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def forward_key(corpus, inputs, model_file, run, extra=()):
|
|
302
|
+
"""The manifest key of a forward run of scripts/engine_step_check.py: corpus (name, input digest), the model
|
|
303
|
+
file's sha256, run (dict: substeps, iterations, nworld, select, tape, fused) and the build of this machine
|
|
304
|
+
(cuda.arch(), the nvcc release, cuda.arch_flags('forward'), the extra nvcc options and cuda.unit_defines)."""
|
|
305
|
+
extra = list(extra)
|
|
306
|
+
return dict(unit="check_forward", corpus=corpus, inputs_sha256=inputs_digest(inputs),
|
|
307
|
+
model_sha256=hashlib.sha256(Path(model_file).read_bytes()).hexdigest(),
|
|
308
|
+
run={k: run[k] for k in sorted(run)},
|
|
309
|
+
build=dict(arch=cuda.arch(), nvcc=provenance.nvcc_version(), forward_flags=cuda.arch_flags("forward"),
|
|
310
|
+
options=extra + cuda.unit_defines("forward", None, extra)))
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def digest_files():
|
|
314
|
+
"""The manifests read by digest_check: DIGESTS, then $DK_DIGESTS when set."""
|
|
315
|
+
out = [DIGESTS]
|
|
316
|
+
if os.environ.get(DIGESTS_ENV):
|
|
317
|
+
out.append(Path(os.environ[DIGESTS_ENV]))
|
|
318
|
+
return out
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _load(path):
|
|
322
|
+
path = Path(path)
|
|
323
|
+
if not path.exists():
|
|
324
|
+
return dict(format=DIGESTS_FORMAT, entries=[])
|
|
325
|
+
d = json.loads(path.read_text())
|
|
326
|
+
if d.get("format") != DIGESTS_FORMAT:
|
|
327
|
+
raise ValueError(f"{path}: format {d.get('format')!r}, expected {DIGESTS_FORMAT}")
|
|
328
|
+
return d
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _same_key(a, b):
|
|
332
|
+
return json.loads(json.dumps(a, sort_keys=True)) == json.loads(json.dumps(b, sort_keys=True))
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def digest_check(arrays, key, files=None):
|
|
336
|
+
"""The outputs (dict name -> array) against the manifests' entry of this key (module docstring): {status: match /
|
|
337
|
+
mismatch / unanchored, arrays: {name: equal} over the names both have, manifest, note}."""
|
|
338
|
+
for f in files or digest_files():
|
|
339
|
+
for e in _load(f)["entries"]:
|
|
340
|
+
if not _same_key(e["key"], key):
|
|
341
|
+
continue
|
|
342
|
+
common = sorted(set(e["outputs"]) & set(arrays))
|
|
343
|
+
same = {k: e["outputs"][k] == array_digest(arrays[k]) for k in common}
|
|
344
|
+
status = "match" if common and all(same.values()) else "mismatch"
|
|
345
|
+
return dict(status=status, arrays=same, manifest=provenance.rel(f), made=e.get("made"),
|
|
346
|
+
note=None if common else "no output in common with the entry")
|
|
347
|
+
return dict(status="unanchored", arrays={}, manifest=None,
|
|
348
|
+
note=f"no entry for this corpus, run and build ({key['build']['arch']}, nvcc {key['build']['nvcc']}) "
|
|
349
|
+
f"in {', '.join(provenance.rel(f) for f in (files or digest_files()))}")
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def digest_write(path, arrays, key, source_sha256=None, replace=False, about=None):
|
|
353
|
+
"""Add the entry of this key with the outputs' digests to the manifest at path (created if missing); an entry
|
|
354
|
+
with this key and other digests is replaced only with replace=True (ValueError otherwise). Returns the status."""
|
|
355
|
+
path = Path(path)
|
|
356
|
+
d = _load(path)
|
|
357
|
+
d.setdefault("about", about or "sha256 digests of scripts/engine_step_check.py's forward outputs per corpus, run "
|
|
358
|
+
"and build (nablaengine.checks)")
|
|
359
|
+
outputs = {k: array_digest(v) for k, v in sorted(arrays.items())}
|
|
360
|
+
made = dict(date=datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d"), gpu=provenance.gpu(),
|
|
361
|
+
source_sha256=source_sha256)
|
|
362
|
+
for i, e in enumerate(d["entries"]):
|
|
363
|
+
if _same_key(e["key"], key):
|
|
364
|
+
if e["outputs"] == outputs:
|
|
365
|
+
return "unchanged"
|
|
366
|
+
if not replace:
|
|
367
|
+
raise ValueError(f"{path}: an entry with this key has other digests (the forward changed); "
|
|
368
|
+
"replace it explicitly")
|
|
369
|
+
d["entries"][i] = dict(key=key, outputs=outputs, made=made)
|
|
370
|
+
break
|
|
371
|
+
else:
|
|
372
|
+
d["entries"].append(dict(key=key, outputs=outputs, made=made))
|
|
373
|
+
d["entries"].sort(key=lambda e: json.dumps(e["key"], sort_keys=True))
|
|
374
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
375
|
+
path.write_text(json.dumps(d, indent=1, sort_keys=True) + "\n")
|
|
376
|
+
return "written"
|