Skip to content

Commit f034f76

Browse files
committed
fix(hstu): match upstream timestamp rounding
Preserve FP32 div-floor and remainder semantics at timestamp boundaries, pass validated stage schemas into network construction, and cover clock encoding against upstream over 100003 inputs. Address review findings in serving: publish cache counters atomically, fence output copies on failure, validate batches before copying, preserve responses when metric publication fails, and keep generation retryable. Tighten public asset redirects and staging precedence, retain input provenance, and require a patched checkpoint loader. Keep prototype deployment within family ownership. Signed-off-by: Yizhuo Zhang <yizhuoz@nvidia.com>
1 parent 7d103a3 commit f034f76

26 files changed

Lines changed: 512 additions & 95 deletions

‎core/api/tests/ranking_test.cpp‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -80,17 +80,18 @@ int main(int argc, char** argv) {
8080
rejects([&] { task.configure_cache(1); }, TRTMC_INVALID_ARGUMENT);
8181
rejects([&] { task.configure_cache(1000, .1); }, TRTMC_INVALID_ARGUMENT);
8282
rejects([&] { task.run({{features, 3}}, {{"unknown", 1}}); }, TRTMC_INVALID_CONFIG);
83+
auto input_guard = load("must_not_run").task<trtmc::StructuredRanking>();
8384
auto bad = features[1];
8485
features[1].name = "continuous";
85-
rejects([&] { task.run({{features, 3}}); }, TRTMC_INVALID_ARGUMENT);
86+
rejects([&] { input_guard.run({{features, 3}}); }, TRTMC_INVALID_ARGUMENT);
8687
features[1] = bad;
8788
features[1].type = static_cast<trtmc::RankingFeatureType>(99);
88-
rejects([&] { task.run({{features, 3}}); }, TRTMC_INVALID_ARGUMENT);
89+
rejects([&] { input_guard.run({{features, 3}}); }, TRTMC_INVALID_ARGUMENT);
8990
features[1] = bad;
9091
features[1].bytes = {};
91-
rejects([&] { task.run({{features, 3}}); }, TRTMC_INVALID_ARGUMENT);
92+
rejects([&] { input_guard.run({{features, 3}}); }, TRTMC_INVALID_ARGUMENT);
9293
features[1] = bad;
93-
rejects([&] { task.run({}); }, TRTMC_INVALID_ARGUMENT);
94+
rejects([&] { input_guard.run({}); }, TRTMC_INVALID_ARGUMENT);
9495
for (const auto* mode : {"bad_shape", "bad_kind", "bad_scores"}) {
9596
auto invalid = load(mode).task<trtmc::StructuredRanking>();
9697
rejects([&] { invalid.run({{features, 3}}); }, TRTMC_INTERNAL_ERROR);

‎families/hstu/README.md‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ adapter; the model graph, cache implementation and tensor schema are shared.
3030
## Build and change the serving profile
3131

3232
Keep downloaded weights, bundles, build products and test results outside the
33-
checkout. Conversion requires PyTorch; building requires TensorRT and NumPy.
33+
checkout. Conversion requires PyTorch 2.10 or newer; building requires TensorRT and NumPy.
3434

3535
```bash
3636
export PYTHONPATH="$PWD/core/builder:$PWD"
@@ -213,6 +213,18 @@ four-field factory/six-argument loader ABI. Do not mix it with a main-built
213213
SDK or assume it applies to another image release. Rebuild serialized engines
214214
when the TensorRT version or target platform changes.
215215

216+
The helper stages HSTU and common SDK libraries. For an image serving other
217+
families, install only its two HSTU libraries into the image's existing SDK
218+
directory during image assembly, and use that SDK directory as `--runtime-root`:
219+
220+
```bash
221+
install -m 755 /tmp/dlrmv3/deploy/libtrtmc_model_hstu.so \
222+
/tmp/dlrmv3/deploy/libhstu_triton.so /usr/lib/x86_64-linux-gnu/
223+
```
224+
225+
This retains the image's other family plugins in their original installation.
226+
Use the original SDK library search path when serving from that directory.
227+
216228
The native serving path loads `libtrtmc_model_hstu.so` directly through the
217229
image's backend. `native_repository.py` generates its configuration;
218230
`libhstu_triton.so` reads bundle metadata for that generator and supports the

‎families/hstu/checkpoint.py‎

Lines changed: 29 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
import argparse
77
import json
8+
import tempfile
89
from pathlib import Path
910
import numpy as np
1011
from .config import Config, ServingProfile
@@ -93,9 +94,12 @@ def validate_weights(weights):
9394
weights[PRE + "_action_encoder._combined_action_weights"], [1, 2, 4, 8, 16]
9495
):
9596
raise ValueError("unsupported action bitmask encoding")
96-
for name in (POST + "_period_units", POST + "_units_per_period"):
97-
if (weights[name] <= 0).any():
98-
raise ValueError("invalid timestamp periods")
97+
for name, expected_periods in (
98+
(POST + "_period_units", [[3600, 86400]]),
99+
(POST + "_units_per_period", [[24, 7]]),
100+
):
101+
if not np.array_equal(weights[name], expected_periods):
102+
raise ValueError("unsupported timestamp periods")
99103
return weights
100104

101105

@@ -117,23 +121,29 @@ def convert(source, output, *, history_length=512, candidates=128):
117121
{k: v.detach().cpu().numpy().copy() for k, v in state["dense_dict"].items()}
118122
)
119123
config = Config(serving=ServingProfile(history_length=history_length, candidates=candidates))
120-
output.mkdir(parents=True, exist_ok=True)
121-
np.savez(output / "dlrmv3_weights.npz", **weights)
122-
config.save(output)
123-
(output / "checkpoint_provenance.json").write_text(
124-
json.dumps(
125-
dict(
126-
model="MLPerf Inference v6.0 DLRMv3",
127-
source=DEFAULT_URL,
128-
license=LICENSE_URL,
129-
scope="complete dense model; sparse embedding lookup is caller-owned",
130-
tensor_count=len(weights),
131-
tensor_bytes=sum(v.nbytes for v in weights.values()),
132-
),
133-
indent=2,
124+
output.parent.mkdir(parents=True, exist_ok=True)
125+
with tempfile.TemporaryDirectory(prefix=f".{output.name}-", dir=output.parent) as temporary:
126+
staged = Path(temporary)
127+
np.savez(staged / "dlrmv3_weights.npz", **weights)
128+
config.save(staged)
129+
(staged / "checkpoint_provenance.json").write_text(
130+
json.dumps(
131+
dict(
132+
model="MLPerf Inference v6.0 DLRMv3",
133+
source=str(Path(source).resolve()),
134+
upstream_reference=DEFAULT_URL,
135+
license=LICENSE_URL,
136+
scope="complete dense model; sparse embedding lookup is caller-owned",
137+
tensor_count=len(weights),
138+
tensor_bytes=sum(v.nbytes for v in weights.values()),
139+
),
140+
indent=2,
141+
)
142+
+ "\n"
134143
)
135-
+ "\n"
136-
)
144+
if output.exists():
145+
output.rmdir() # Only the previously allowed empty destination.
146+
staged.rename(output)
137147
return config
138148

139149

‎families/hstu/model.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ def build(request, writer):
6969
writer.add_json("runtime.json", runtime)
7070
for stage in runtime["stages"]:
7171
network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED))
72-
owner = Network(network, config, weights, request.precision).define(stage["name"])
72+
owner = Network(network, config, weights, request.precision).define(stage)
7373
profile = builder.create_optimization_profile()
7474
for i in range(network.num_inputs):
7575
tensor = network.get_input(i)

‎families/hstu/native.py‎

Lines changed: 42 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -337,29 +337,7 @@ def score_candidates(self, inp):
337337
self.mul(self.cast(self_weight, trt.float32), self_val),
338338
)
339339
x = self.finish(x, u, attended, layer)
340-
timestamp = self.cast(self.reshape(inp["query_timestamp_b"], (-1, 1, 1)), trt.float32)
341-
units = self.n.add_unary(
342-
self.op(timestamp, self.const(self.w[POST + "_period_units"].reshape(1, 1, 2)), "DIV"),
343-
trt.UnaryOperation.FLOOR,
344-
).get_output(0)
345-
periods = self.const(self.w[POST + "_units_per_period"].reshape(1, 1, 2))
346-
remainder = self.op(
347-
units,
348-
self.mul(
349-
self.n.add_unary(
350-
self.op(units, periods, "DIV"), trt.UnaryOperation.FLOOR
351-
).get_output(0),
352-
periods,
353-
),
354-
"SUB",
355-
)
356-
phase = self.mul(self.op(remainder, periods, "DIV"), self.const([2 * 3.14], np.float32))
357-
cos = self.n.add_unary(phase, trt.UnaryOperation.COS).get_output(0)
358-
sin = self.n.add_unary(phase, trt.UnaryOperation.SIN).get_output(0)
359-
features = self.reshape(
360-
self.concat([self.reshape(cos, (-1, 1, 2, 1)), self.reshape(sin, (-1, 1, 2, 1))], 3),
361-
(-1, 1, 4),
362-
)
340+
features = self.timestamp_features(inp["query_timestamp_b"])
363341
features = self.add(
364342
self.mul(self.slice_last(x, 0, 4), self.const([0], np.float32)), features
365343
)
@@ -384,11 +362,48 @@ def score_candidates(self, inp):
384362
)
385363
]
386364

387-
def define(self, stage):
388-
batch = max(self.c.serving.min_batch_size, self.c.serving.opt_batch_size)
389-
schema = next(
390-
s for s in self.c.runtime(batch, self.precision)["stages"] if s["name"] == stage
365+
def timestamp_features(self, query_timestamp):
366+
timestamp = self.cast(self.reshape(query_timestamp, (-1, 1, 1)), trt.float32)
367+
# Upstream uses div(..., rounding_mode="floor"), whose fmod-based
368+
# correction differs from floor(a / b) at FP32 timestamp boundaries.
369+
integer_time = self.cast(timestamp, trt.int64)
370+
divisor = self.const(self.w[POST + "_period_units"].astype(np.int64).reshape(1, 1, 2))
371+
modulo = self.op(
372+
integer_time, self.mul(self.op(integer_time, divisor, "FLOOR_DIV"), divisor), "SUB"
373+
)
374+
division = self.op(
375+
self.op(timestamp, self.cast(modulo, trt.float32), "SUB"),
376+
self.const(self.w[POST + "_period_units"].reshape(1, 1, 2)),
377+
"DIV",
391378
)
379+
floored = self.n.add_unary(division, trt.UnaryOperation.FLOOR).get_output(0)
380+
units = self.select(
381+
self.op(self.op(division, floored, "SUB"), self.const([0.5], np.float32), "GREATER"),
382+
self.add(floored, self.const([1], np.float32)),
383+
floored,
384+
)
385+
integer_units = self.cast(units, trt.int64)
386+
periods = self.const(self.w[POST + "_units_per_period"].reshape(1, 1, 2))
387+
integer_periods = self.cast(periods, trt.int64)
388+
remainder = self.cast(
389+
self.op(
390+
integer_units,
391+
self.mul(self.op(integer_units, integer_periods, "FLOOR_DIV"), integer_periods),
392+
"SUB",
393+
),
394+
trt.float32,
395+
)
396+
phase = self.mul(self.op(remainder, periods, "DIV"), self.const([2 * 3.14], np.float32))
397+
cos = self.n.add_unary(phase, trt.UnaryOperation.COS).get_output(0)
398+
sin = self.n.add_unary(phase, trt.UnaryOperation.SIN).get_output(0)
399+
features = self.reshape(
400+
self.concat([self.reshape(cos, (-1, 1, 2, 1)), self.reshape(sin, (-1, 1, 2, 1))], 3),
401+
(-1, 1, 4),
402+
)
403+
return features
404+
405+
def define(self, schema):
406+
stage = schema["name"]
392407
dtype = {"int64": trt.int64, "int32": trt.int32, "float32": trt.float32}
393408
inp = {
394409
s["name"]: self.n.add_input(s["name"], dtype[s["dtype"]], s["shape"])

‎families/hstu/reference.py‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,13 @@ def sigmoid(x):
2020
return np.exp(-np.logaddexp(np.float32(0), -x))
2121

2222

23+
def timestamp_features(timestamp, period_units, units_per_period):
24+
"""Match upstream FP32 floor division/remainder before periodic features."""
25+
units = np.floor_divide(timestamp.astype(np.float32)[..., None], period_units)
26+
phase = np.remainder(units, units_per_period) / units_per_period * np.float32(2 * 3.14)
27+
return np.stack([np.cos(phase), np.sin(phase)], -1).reshape(len(timestamp), 1, 4)
28+
29+
2330
class Reference:
2431
def __init__(self, config, weights):
2532
self.c = config
@@ -126,16 +133,9 @@ def score(self, inputs):
126133
)
127134
x += np.concatenate([u, attn, gated], -1) @ w[p + "_output_weight"]
128135
user = x[:, t + 1 :]
129-
# Timestamp arithmetic is FP32 before floor/remainder, matching upstream.
130-
units = np.floor(
131-
inputs["query_timestamp"].astype(np.float32)[..., None] / w[POST + "_period_units"]
132-
)
133-
phase = (
134-
np.remainder(units, w[POST + "_units_per_period"])
135-
/ w[POST + "_units_per_period"]
136-
* np.float32(2 * 3.14)
136+
time_features = timestamp_features(
137+
inputs["query_timestamp"], w[POST + "_period_units"], w[POST + "_units_per_period"]
137138
)
138-
time_features = np.stack([np.cos(phase), np.sin(phase)], -1).reshape(b, 1, 4)
139139
user = self.ln(
140140
self.linear(
141141
np.concatenate([user, np.broadcast_to(time_features, (b, c, 4))], -1),

‎families/hstu/requirements.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
numpy>=1.26,<3
2-
torch>=2.6
2+
torch>=2.10.0

‎families/hstu/runtime/history_cache.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,5 +27,6 @@ class IHistoryCache {
2727
virtual nlohmann::json history_info(const std::string& handle) = 0;
2828
virtual void release_history(const std::vector<std::string>& handles) = 0;
2929
virtual nlohmann::json history_stats() const = 0;
30+
virtual nlohmann::json cache_snapshot() const = 0;
3031
};
3132
} // namespace trtmc::hstu

‎families/hstu/runtime/staged_pipeline.cpp‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -152,16 +152,27 @@ std::vector<FeatureTensor> StagedPipeline::run_step(std::int64_t batch) {
152152
step_->forward_device_async({});
153153
increment("decode_step_calls_total");
154154
std::vector<FeatureTensor> outputs;
155+
outputs.reserve(config_.at("outputs").size());
155156
for (const auto& spec : config_.at("outputs")) {
156157
auto shape = spec.at("shape").get<std::vector<std::int64_t>>();
157158
shape.at(0) = batch;
158159
FeatureTensor output{spec.at("name"), parse_dtype(spec.at("dtype")), shape, {}};
159160
output.bytes.resize(checked_bytes(shape, output.dtype));
160-
check(cudaMemcpyAsync(output.bytes.data(), step_->device_ptr(output.name),
161-
output.bytes.size(), cudaMemcpyDeviceToHost, stream));
162161
outputs.push_back(std::move(output));
163162
}
163+
struct CopyFence {
164+
cudaStream_t stream;
165+
bool pending{true};
166+
~CopyFence() {
167+
if (pending)
168+
cudaStreamSynchronize(stream);
169+
}
170+
} fence{stream};
171+
for (auto& output : outputs)
172+
check(cudaMemcpyAsync(output.bytes.data(), step_->device_ptr(output.name),
173+
output.bytes.size(), cudaMemcpyDeviceToHost, stream));
164174
check(cudaStreamSynchronize(stream));
175+
fence.pending = false;
165176
return outputs;
166177
}
167178

@@ -173,6 +184,18 @@ nlohmann::json StagedPipeline::history_stats() const {
173184
std::lock_guard<std::mutex> lock(stats_mutex_);
174185
return history_stats_;
175186
}
187+
nlohmann::json StagedPipeline::cache_snapshot() const {
188+
std::lock_guard<std::mutex> lock(stats_mutex_);
189+
auto result = history_stats_;
190+
result.update({{"supported", stats_.supported},
191+
{"budget_bytes", stats_.budget_bytes},
192+
{"reserved_bytes", stats_.reserved_bytes},
193+
{"used_bytes", stats_.used_bytes},
194+
{"peak_bytes", stats_.peak_bytes},
195+
{"active_sequences", stats_.active_sequences},
196+
{"allocation_failures", stats_.allocation_failures}});
197+
return result;
198+
}
176199
void StagedPipeline::require_history(bool enabled) const {
177200
if (!request_)
178201
throw std::invalid_argument(

‎families/hstu/runtime/staged_pipeline.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ class StagedPipeline final : public trtmc::IStructuredRanking,
4141
nlohmann::json history_info(const std::string&) override;
4242
void release_history(const std::vector<std::string>&) override;
4343
nlohmann::json history_stats() const override;
44+
nlohmann::json cache_snapshot() const override;
4445

4546
private:
4647
std::unique_ptr<ITrtModule> prepare_, step_, request_;

0 commit comments

Comments
 (0)