Archived
radiance 1.16.0
New models:
- Hunyuan3D-2 (hunyuan3d2): an untextured 3-D mesh from one picture of an object. DINOv2-giant
over the picture, a FLUX-shaped flow-matching DiT (16 double-stream and 32 single-stream blocks
of 1024) over 3072 latents with both guidance branches in one step, and the shape VAE's
geometry decoder. Converted from tencent/Hunyuan3D-2's hunyuan3d-dit-v2-0 folder with
data/recipes/hunyuan3d-2-bf16.recipe (fp16 cast to bf16, 4.4 GiB, one card). The licence
(Tencent Hunyuan 3D 2.0 Community License) does not cover the EU, the UK or South Korea
- Served on Hunyuan3D-2's own API server routes, so its Blender add-on and scripts work
unchanged: POST /generate answers with the mesh, POST /send runs it in the background and
GET /status/{uid} reports steps_done and then the file. GLB, OBJ, PLY or STL; the field is
sampled coarse to fine as FlashVDM's hierarchical decoding does, or densely with
"volume_decoding": "dense"; seed, steps, guidance and octree_resolution as the reference.
Texturing (Hunyuan3D-Paint) is refused for now (docs/GUIDE.md §5.17)
Merged:
- libr3d rewritten for RDNA3's wave matrix (@RikshaDriver): bf16, f16, int8-activation and vocab
GEMMs retiled to 16x128 blocks with a double-buffered k-walk; fp8, mxfp4a8, w2a8, w4a16, w5a16
and w8a8 quantised GEMMs and the gated form; grouped MoE GEMMs (bf16, fp8a8f32, mxfp4a8); the
norms and quantisers, the QSA state ops and the MoE router, scatter and gather. Brought onto the
op contract before release (13 schemas, the MoE GEMMs on weight tables with a_order and bf16
output, moe_gather's gate pitch, moe_scatter above 1024 slots, the mxfp4 m16 dispatch) and its
gated-delta-net kernels replaced by libhalo's; every op it serves now passes rad-kbench against
libref on a gfx1151, and r3d_selftest checks its MoE GEMMs by value
- Gemma 4 31B: asymmetric int5 linears (w5a8i8 above 64 rows, w5a16 up to 64, a scale per 128),
the norm, GELU and two-rank all-reduce junctions at quant_act_i8g's grid (rmsnorm_quant_i8g,
gelu_mul_quant_i8g, ar_rmsnorm_quant_i8g) so the prefill overlap runs on the i8a8, a4 and w5
trunks, and compose files for the 31B i8g, heretic-ara-i8g and w5 on two cards (@keptn42)
- The norms' lane sum reads eight at a time: TranslateGemma 27B decode is back from 225 to 239
tok/s a stream at four streams, bit for bit the same output (@mici81)
- The head-256 prefill softmax rescales each row by its own maximum, not by a vote of the wave, so
a row's rounding no longer depends on which rows share its launch (@gostar)
Anthropic Messages API:
- /v1/messages takes min_p, presence_penalty, frequency_penalty, repetition_penalty and
repeat_last_n as top-level fields with the chat path's names, ranges and meaning, so clients that
speak only the Anthropic format (Claude Code) can set a model card's sampling, such as Qwen's
presence_penalty 1.5. The penalties count the last repeat_last_n tokens of prompt and reply (64
by default, --repeat-last-n), as llama.cpp does
Plugin ABI 33:
- Shape generators: rad_declare_shape_generator, RadShapeGenBatch (RadBatch::sgen_b) and
RadArchProbe::gen_shape, with the SCOND, SSTEP, SLATENT and SQUERY passes. The layout
fingerprint table is regenerated; out-of-tree plugins rebuild against 33
- New op point_fourier ([x | sin(x 2^j) | cos(x 2^j)], times pi on request) in libref, libavx,
libr4d and libhalo
- A checkpoint for a model that reads no text gets a one-token vocabulary
More cards from the one image:
- stilldeadcode/radiance now carries libr3d (RDNA3: gfx11-generic, every gfx11 chip) and libhalo
(Strix Halo: gfx1151, preferred there over libr3d) beside libr4d (gfx1201). docker/build.sh and
the Dockerfile default to gfx1201;gfx11-generic;gfx1151
- libr3d loads only where the KFD topology lists a gfx11 card and libhalo only where it lists a
gfx1151; a process without /dev/kfd sees neither. On an RDNA4 card, or with no card at all,
the image therefore behaves exactly as before, and rad-convert lays weights out as before
- libhalo and libr3d now declare gemm_nt_q's w_rb, and libhalo gram_accum's upper, as libr4d
does. Before, any build carrying them refused both at load ("9 parameters vs 8"), so a build
for Strix Halo or RDNA3 had no device kernel library
- libhalo does not yet have every op libr4d added after it was ported (the IQR rows, Pixtral and
Ministral rope, the tree-attention and DFlash-tree rows, among others); halo_parity lists them
and is left out of the image's test stage until they are ported
Fixed -- container and checkpoint parsing:
- A .rad expert-1 entry inside or before expert 0 is refused; a vocab section whose count names
an array at offset 0 is refused rather than read from the file header; offset checks no longer
wrap; header tables must sit on their element alignment
- An imatrix array of arrays (unbounded recursion) and a safetensors header naming a tensor twice
are refused; a failed RadWriter undo says the container is damaged; a tune cache measured on
another machine is refused, as its format contract says
Fixed -- plugins:
- Two plugins declaring one op with different parameter roles are refused; before, the core
applied the first one's chunk/capacity roles to the other's rows
- Null tables behind nonzero counts, unknown roles, keyless parameters or constraints and more
operands than an issue carries are refused by name at load; on the host backend device rows are
dropped even when no fat binary was registered; rad-schemas checks the ABI layout fingerprint as
the engine does
Fixed -- device:
- Stream slots are recycled under a new generation: before, 1024 stream create/destroy cycles
(LoRA loads, lanes, uplinks) made every later rad_stream_create fail
- A stream whose drain fails keeps its queue and kernarg ring instead of freeing them under the
card; the kernarg ring no longer leaks when its access grant fails; a block over 1024 work-items
is refused
- rad_dev_free takes the allocation off the ledger the pin-cap check reads; the host backend
charges pages to the card the range was reserved for
Fixed -- engine and server:
- Two NDEBUG-only asserts (runtime-window totals, ring blocks per group) are refusals; a
plugin-declared lcm past int64 saturates so the quantum check refuses it; every share view rect
and part span is bounded by its entry
- Video: the timestep regions hold the refine rungs a schedule appends, a zero-frame encode is
refused, /v1/videos bounds each side before the area product, and a realtime session needs a
clip length to cut a turn at
Fixed -- kernels and quantisation:
- A trellis run shorter than a state's codes (tcq_rows=1, or N % tcq_rows == 1) read its seam
out of bounds; the encoder now refuses it as the decoder does, and tcq_rows below one state is
refused at parse
- qsa_tail_store bounds its slot index by the state plane (libr4d and libhalo); paged attention
refuses kv_heads <= 0; libavx row_amax skips a NaN as libref does
Fixed -- tools:
- pad_tp.py no longer runs cp through a shell with shard names from the checkpoint's index
(quote injection, path traversal): names must be bare file names
- ops_doc_check.sh runs under mawk (Ubuntu's awk); rad-kbench --max-cases/--max-bytes are checked
integers; oot_plugins fails unless the installed replay passed a case and failed none
Thanks to @RikshaDriver, @keptn42, @mici81 and @gostar.
This commit is contained in:
1 parent
cfa6a668f6
commit
769b4c64a6
122 files changed
+10092
-2203
No files matched your search
@@ -390,7 +390,7 @@ json Server::capabilities() const {
|
||||
caps["reasoning"] = !rerank && deps_.chat && deps_.chat->supports_reasoning();
|
||||
/* An image model reads pictures only for edits and writes no text a grammar could constrain,
|
||||
* whatever its conditioning network's processor would take. */
|
||||
const bool img = opt_.image_model || opt_.video_model;
|
||||
const bool img = opt_.image_model || opt_.video_model || opt_.shape_model;
|
||||
caps["grammar"] = !img && !rerank && deps_.grammar != nullptr;
|
||||
/* Laya runs on the embedding path, but answers /v1/systemone, not /v1/embeddings. */
|
||||
caps["embedding"] = deps_.embed != nullptr && !rerank && opt_.decision_type != "laya";
|
||||
@@ -403,11 +403,13 @@ json Server::capabilities() const {
|
||||
caps["image_edit"] = deps_.images != nullptr && deps_.images->info().max_refs > 0;
|
||||
caps["audio_generation"] = deps_.audio != nullptr;
|
||||
caps["video_generation"] = deps_.videos != nullptr;
|
||||
caps["shape_generation"] = deps_.shapes != nullptr;
|
||||
/* The decision protocol /v1/systemone serves (ServerOptions::decision_type), so a proxy can
|
||||
* route to a decision model without trying a generation; null when it serves none. */
|
||||
caps["decision"] = opt_.decision_type.empty() ? json(nullptr) : json(opt_.decision_type);
|
||||
/* What a video request may carry. */
|
||||
if (deps_.videos) video_caps(caps, deps_.videos);
|
||||
if (deps_.shapes) shape_caps(caps, deps_.shapes);
|
||||
/* The efforts a chat request may send, probed from the template at startup; null when it
|
||||
* takes any word. "none" and "minimal" are this server's and turn thinking off. */
|
||||
if (lim_.reasoning_efforts.empty()) {
|
||||
|
||||
+16
-1
@@ -22,7 +22,8 @@
|
||||
struct RadModelMeta;
|
||||
|
||||
namespace rad {
|
||||
namespace gen { struct Request; struct AudioRequest; class AudioTicket; struct VideoRequest; class VideoTicket; }
|
||||
namespace gen { struct Request; struct AudioRequest; class AudioTicket; struct VideoRequest; class VideoTicket;
|
||||
struct ShapeRequest; struct ShapeGenInfo; }
|
||||
namespace mm { struct Frame; struct Item; }
|
||||
namespace server {
|
||||
|
||||
@@ -816,5 +817,19 @@ public:
|
||||
virtual int64_t running() const = 0;
|
||||
};
|
||||
|
||||
/* The shape generator (core/gen/shape_driver.h), for a model that makes a 3-D shape from a
|
||||
* picture: its declared picture, sampler and grid (gen::ShapeGenInfo) and its request queue. The
|
||||
* server prepares the picture (gen::shape_picture), queues the request, and meshes the field the
|
||||
* ticket hands back. */
|
||||
class IShapeGen {
|
||||
public:
|
||||
virtual ~IShapeGen() = default;
|
||||
virtual const gen::ShapeGenInfo& info() const = 0;
|
||||
/* Queue a request; refused at once, with `why`, when it can never run. */
|
||||
virtual int submit(std::unique_ptr<gen::ShapeRequest> r, std::string* why) = 0;
|
||||
virtual int64_t queued() const = 0;
|
||||
virtual int64_t running() const = 0;
|
||||
};
|
||||
|
||||
} /* namespace server */
|
||||
} /* namespace rad */
|
||||
+11
-3
@@ -3379,11 +3379,16 @@ int anthropic_image(const json& block, const std::string& at, json* out, ApiErro
|
||||
* continuation sends only the tail of the conversation), so a field outside these lists is
|
||||
* refused by name rather than ignored. The refusal says "Extra inputs are not permitted", as
|
||||
* Anthropic's does; Claude Code matches those words to retry without a beta field it can
|
||||
* drop. */
|
||||
* drop.
|
||||
*
|
||||
* The last row is not Anthropic's: the chat path's history penalties and min-p, under the chat
|
||||
* path's names, ranges and meaning, for clients that speak only this format to a model whose
|
||||
* card asks for them (Qwen's presence_penalty). */
|
||||
const char* kAnthropicFields[] = {
|
||||
"model", "messages", "system", "max_tokens", "temperature", "top_p", "top_k", "stream",
|
||||
"stop_sequences", "tools", "tool_choice", "thinking", "metadata", "output_config",
|
||||
"output_format", "context_management", "thread",
|
||||
"min_p", "presence_penalty", "frequency_penalty", "repetition_penalty", "repeat_last_n",
|
||||
};
|
||||
|
||||
/* Accepted and not acted on: none of them can change the answer here. Capacity and placement
|
||||
@@ -3917,8 +3922,11 @@ int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string
|
||||
if (one) o["parallel_tool_calls"] = false;
|
||||
}
|
||||
|
||||
/* `model` included, since the reply names it back as Anthropic's does. */
|
||||
for (const char* k : { "model", "max_tokens", "temperature", "top_p", "top_k", "stream" })
|
||||
/* `model` included, since the reply names it back as Anthropic's does. The penalties and
|
||||
* min-p are the chat path's own fields, checked there. */
|
||||
for (const char* k : { "model", "max_tokens", "temperature", "top_p", "top_k", "stream",
|
||||
"min_p", "presence_penalty", "frequency_penalty", "repetition_penalty",
|
||||
"repeat_last_n" })
|
||||
if (b.contains(k)) o[k] = b.at(k);
|
||||
if (b.contains("stop_sequences")) o["stop"] = b.at("stop_sequences");
|
||||
|
||||
|
||||
@@ -220,6 +220,12 @@ void Server::handle_realtime(const HttpRequest& req, WsConn& ws) {
|
||||
"this model does not transcribe: its architecture plugin states no "
|
||||
"transcription format (rad_arch_audio_format), or it was started without "
|
||||
"its audio encoder", 1008);
|
||||
/* An open turn is cut at the encoder's clip length; without one it would grow for as long as
|
||||
* the client appends audio. */
|
||||
if (deps_.mm->audio_max_samples() <= 0)
|
||||
return refuse("invalid_request_error", "model_not_supported",
|
||||
"this model's audio encoder states no clip length, which a realtime turn "
|
||||
"is cut at", 1008);
|
||||
/* A session holds a connection's thread and one of its own for its whole life, and runs one
|
||||
* pass at a time: more sessions than the engine has sequences would only queue. */
|
||||
const int64_t cap = std::max<int64_t>(1, opt_.max_seqs);
|
||||
|
||||
@@ -134,6 +134,10 @@ void Server::register_routes() {
|
||||
[this](const HttpRequest& q) { return handle_video_delete(q); });
|
||||
router_.get ("/v1/videos/:id/content",
|
||||
[this](const HttpRequest& q) { return handle_video_content(q); });
|
||||
/* Hunyuan3D-2's API server: a shape from a picture. */
|
||||
router_.post("/generate", [this](const HttpRequest& q) { return handle_shape_generate(q); });
|
||||
router_.post("/send", [this](const HttpRequest& q) { return handle_shape_send(q); });
|
||||
router_.get ("/status/:uid", [this](const HttpRequest& q) { return handle_shape_status(q); });
|
||||
router_.post("/v1/audio/transcriptions",
|
||||
[this](const HttpRequest& q) { return handle_transcription(q); });
|
||||
/* The same, live over a WebSocket (OpenAI's realtime transcription session). A plain GET
|
||||
@@ -374,6 +378,7 @@ void Server::stop() {
|
||||
stopping_.store(true);
|
||||
transport_.stop();
|
||||
stop_videos();
|
||||
stop_shapes();
|
||||
drain_graveyard(2000);
|
||||
}
|
||||
|
||||
@@ -1389,6 +1394,8 @@ std::optional<HttpResponse> Server::refuse_text(const std::string& peer, ApiShap
|
||||
"generates no text"
|
||||
: opt_.video_model ? "this is a video model: it serves /v1/videos and generates "
|
||||
"no text"
|
||||
: opt_.shape_model ? "this is a 3-D shape model: it serves /generate and generates "
|
||||
"no text"
|
||||
: nullptr;
|
||||
if (!why) return std::nullopt;
|
||||
return error_response(err_not_implemented(why), peer, shape);
|
||||
@@ -1675,6 +1682,7 @@ HttpResponse Server::serve_pooled(const HttpRequest& req, bool rerank) {
|
||||
opt_.image_model ? "/v1/embeddings requires an embedding model; this one makes images"
|
||||
: opt_.audio_model ? "/v1/embeddings requires an embedding model; this one makes audio"
|
||||
: opt_.video_model ? "/v1/embeddings requires an embedding model; this one makes video"
|
||||
: opt_.shape_model ? "/v1/embeddings requires an embedding model; this one makes shapes"
|
||||
: "/v1/embeddings requires an embedding model; this one generates "
|
||||
"text"), req.peer);
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ struct Deps {
|
||||
IImageGen* images = nullptr; /* absent -> the images endpoints are 501 */
|
||||
IAudioGen* audio = nullptr; /* absent -> /v1/audio/speech is 501 */
|
||||
IVideoGen* videos = nullptr; /* absent -> /v1/videos is 501 */
|
||||
IShapeGen* shapes = nullptr; /* absent -> /generate is 501 */
|
||||
const SpeechFormat* speech = nullptr; /* absent -> /v1/audio/transcriptions is 501 */
|
||||
|
||||
/* Engine-side state the server cannot see (per-card VRAM, the expert plane), as a snapshot
|
||||
@@ -88,6 +89,10 @@ struct ServerOptions {
|
||||
* many finished videos are kept at most (the oldest go first). */
|
||||
int64_t video_ttl_s = 3600;
|
||||
int64_t max_videos = 32;
|
||||
/* A shape generator (rad_declare_shape_generator) generates no text either: the text
|
||||
* endpoints answer 501 naming /generate. A shape made through /send is kept for /status for
|
||||
* as long as a video, as many at most. */
|
||||
bool shape_model = false;
|
||||
/* The decision protocol from the container's `decision.type`: "d1" serves /v1/systemone
|
||||
* (systemone.h), "clef" serves it through the head on the card (clef.h), "laya" through the
|
||||
* Laya plugin's option logits (laya.h), "mica" through Mica's label logits (mica.h); empty
|
||||
@@ -264,6 +269,7 @@ private:
|
||||
struct RealtimeSession; /* realtime.cpp */
|
||||
struct SpeechSession; /* speech_stream.cpp */
|
||||
struct VideoJob; /* videos.cpp */
|
||||
struct ShapeJob; /* shapes.cpp */
|
||||
struct StreamState;
|
||||
|
||||
static UsageOut usage_of(const OaiRequest& r, const std::vector<Generation>& gens);
|
||||
@@ -366,6 +372,17 @@ private:
|
||||
/* What this deployment can do (chat, tools, reasoning, grammar, media, logprobs, reasoning
|
||||
* efforts), shared by /server_info's `capabilities` and the model entry so they agree. */
|
||||
json capabilities() const;
|
||||
/* ------------------------------------------------------------------ shapes.cpp
|
||||
* Hunyuan3D-2's own API: a shape from a picture, made at once (/generate) or in the
|
||||
* background (/send) and collected (/status/{uid}). */
|
||||
HttpResponse handle_shape_generate(const HttpRequest& req);
|
||||
HttpResponse handle_shape_send(const HttpRequest& req);
|
||||
HttpResponse handle_shape_status(const HttpRequest& req);
|
||||
void shape_work(std::shared_ptr<ShapeJob> j);
|
||||
void sweep_shapes_locked(int64_t now);
|
||||
void stop_shapes();
|
||||
static void shape_caps(json& caps, const IShapeGen* gen);
|
||||
|
||||
/* A video model's capabilities (videos.cpp). */
|
||||
static void video_caps(json& caps, const IVideoGen* gen);
|
||||
HttpResponse handle_reset_prefix_cache(const HttpRequest& req);
|
||||
@@ -453,6 +470,9 @@ private:
|
||||
std::mutex videos_m_;
|
||||
std::vector<std::shared_ptr<VideoJob>> videos_;
|
||||
std::vector<std::shared_ptr<VideoJob>> videos_gone_;
|
||||
/* The background shapes (/send), oldest first, and their threads (shapes.cpp). */
|
||||
std::mutex shapes_m_;
|
||||
std::vector<std::shared_ptr<ShapeJob>> shapes_;
|
||||
};
|
||||
|
||||
} /* namespace server */
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
/* shapes.cpp -- Hunyuan3D-2's API over a shape generator (core/gen/shape_driver.h): a 3-D shape
|
||||
* from one picture.
|
||||
*
|
||||
* The routes and fields are the reference's own API server's (hy3dgen's api_server.py), so its
|
||||
* clients (its Blender add-on, scripts written against it) work unchanged:
|
||||
*
|
||||
* POST /generate the shape, made while the request waits, as the file itself;
|
||||
* POST /send the same in the background, answered at once with {"uid"};
|
||||
* GET /status/{uid} {"status": "processing"}, or "completed" with the file as
|
||||
* `model_base64`, or "error" with its `message`.
|
||||
*
|
||||
* The body is JSON: `image`, the picture as base64 (or a data URL), with an alpha channel for a
|
||||
* cut-out object -- the reference removes the background of an opaque picture with rembg, which
|
||||
* this server does not, so an opaque picture is taken whole; `seed` (1234 when absent, as the
|
||||
* reference), `octree_resolution`, `num_inference_steps` and `guidance_scale` (the model's own
|
||||
* when absent), and `type`, the file: glb (the default), obj, ply or stl. `volume_decoding`
|
||||
* "dense" samples every point of the grid instead of refining it coarse to fine. Texturing
|
||||
* (`texture` true) and the reference's text-to-image and re-texturing inputs (`text`, `mesh`)
|
||||
* are refused. The reference's knobs that change nothing here are taken and ignored: `face_count`
|
||||
* (texturing's face budget), `num_chunks` (its decoder's batch) and `mc_algo` "mc"; any other
|
||||
* field is refused by name. A finished background shape is kept for as long as a video, as many
|
||||
* as videos.
|
||||
*/
|
||||
#include "server.h"
|
||||
#include "oai.h"
|
||||
|
||||
#include "gen/shape.h"
|
||||
#include "mm/media.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <thread>
|
||||
|
||||
namespace rad {
|
||||
namespace server {
|
||||
|
||||
namespace {
|
||||
|
||||
/* The largest picture decoded, as the image endpoints bound theirs. */
|
||||
constexpr int64_t kMaxSourcePixels = (int64_t)1 << 26;
|
||||
|
||||
/* A request as the routes read it, and its file's format. */
|
||||
struct ShapeAsk {
|
||||
std::unique_ptr<gen::ShapeRequest> req;
|
||||
std::string type = "glb";
|
||||
};
|
||||
|
||||
int read_ask(const HttpRequest& q, const OaiLimits& lim, const gen::ShapeGenInfo& info,
|
||||
ShapeAsk* out, ApiError* err) {
|
||||
json b;
|
||||
if (parse_request_object(q.body, lim, &b, err) < 0) return RAD_E_INVAL;
|
||||
auto bad = [&](const std::string& p, const std::string& why) {
|
||||
*err = err_bad(p, why);
|
||||
return RAD_E_INVAL;
|
||||
};
|
||||
static const char* const kFields[] = { "image", "seed", "octree_resolution",
|
||||
"num_inference_steps", "guidance_scale", "type",
|
||||
"volume_decoding", "texture", "text", "mesh",
|
||||
"face_count", "num_chunks", "mc_algo" };
|
||||
for (auto it = b.begin(); it != b.end(); ++it) {
|
||||
bool known = false;
|
||||
for (const char* k : kFields) known = known || it.key() == k;
|
||||
if (!known)
|
||||
return bad(it.key(), "'" + it.key() + "' is not a field of /generate");
|
||||
}
|
||||
if (b.contains("mc_algo") && !b["mc_algo"].is_null() &&
|
||||
!(b["mc_algo"].is_string() && b["mc_algo"].get<std::string>() == "mc")) {
|
||||
*err = err_unsupported("mc_algo", "the surface is marching cubes ('mc'); differentiable "
|
||||
"marching cubes ('dmc') is not served");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (const char* k : { "text", "mesh" })
|
||||
if (b.contains(k) && !b[k].is_null()) {
|
||||
*err = err_unsupported(k, std::string("this server makes a shape from a picture; '") +
|
||||
k + "' (the reference's text-to-image and re-texturing "
|
||||
"inputs) is not served");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (b.contains("texture") && b["texture"].is_boolean() && b["texture"].get<bool>()) {
|
||||
*err = err_unsupported("texture", "texturing (Hunyuan3D-Paint) is not served: this "
|
||||
"server makes the untextured shape");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!b.contains("image") || !b["image"].is_string() || b["image"].get<std::string>().empty())
|
||||
return bad("image", "'image' must be the picture as base64");
|
||||
std::string img = b["image"].get<std::string>();
|
||||
if (img.rfind("data:", 0) == 0) {
|
||||
const size_t comma = img.find(',');
|
||||
if (comma == std::string::npos || img.compare(comma - 7, 7, ";base64") != 0)
|
||||
return bad("image", "a data URL must be base64 ('data:<type>;base64,...')");
|
||||
img = img.substr(comma + 1);
|
||||
}
|
||||
std::vector<uint8_t> bytes;
|
||||
if (!base64_decode(img, &bytes) || bytes.empty())
|
||||
return bad("image", "'image' is not valid base64");
|
||||
mm::FrameRGBA f;
|
||||
std::string why;
|
||||
if (mm::decode_image_rgba(bytes.data(), bytes.size(), kMaxSourcePixels, &f, &why) < 0)
|
||||
return bad("image", "the picture could not be decoded: " + why);
|
||||
|
||||
auto r = std::make_unique<gen::ShapeRequest>();
|
||||
if (gen::shape_picture(info, f, &r->patches, &why) < 0) return bad("image", why);
|
||||
auto int_field = [&](const char* k, int64_t lo, int64_t hi, int32_t* v) {
|
||||
if (!b.contains(k) || b[k].is_null()) return true;
|
||||
if (!b[k].is_number_integer() || b[k].get<int64_t>() < lo || b[k].get<int64_t>() > hi) {
|
||||
bad(k, std::string("'") + k + "' must be an integer " + std::to_string(lo) + ".." +
|
||||
std::to_string(hi));
|
||||
return false;
|
||||
}
|
||||
*v = (int32_t)b[k].get<int64_t>();
|
||||
return true;
|
||||
};
|
||||
if (!int_field("num_inference_steps", 2, info.max_steps, &r->steps) ||
|
||||
!int_field("octree_resolution", info.min_resolution, info.max_resolution,
|
||||
&r->resolution))
|
||||
return RAD_E_INVAL;
|
||||
if (b.contains("guidance_scale") && !b["guidance_scale"].is_null()) {
|
||||
if (!b["guidance_scale"].is_number() || !(b["guidance_scale"].get<double>() >= 0.0) ||
|
||||
!std::isfinite(b["guidance_scale"].get<double>()))
|
||||
return bad("guidance_scale", "'guidance_scale' must be a finite number, not negative");
|
||||
r->guidance = b["guidance_scale"].get<double>();
|
||||
}
|
||||
r->seed = 1234;
|
||||
if (b.contains("seed") && !b["seed"].is_null()) {
|
||||
if (!b["seed"].is_number_integer())
|
||||
return bad("seed", "'seed' must be an integer");
|
||||
r->seed = b["seed"].is_number_unsigned() ? b["seed"].get<uint64_t>()
|
||||
: (uint64_t)b["seed"].get<int64_t>();
|
||||
}
|
||||
if (b.contains("volume_decoding") && !b["volume_decoding"].is_null()) {
|
||||
const std::string v = b["volume_decoding"].is_string()
|
||||
? b["volume_decoding"].get<std::string>() : "";
|
||||
if (v != "hierarchical" && v != "dense")
|
||||
return bad("volume_decoding", "'volume_decoding' is hierarchical or dense");
|
||||
r->dense = v == "dense";
|
||||
}
|
||||
if (b.contains("type") && !b["type"].is_null()) {
|
||||
if (!b["type"].is_string()) return bad("type", "'type' is glb, obj, ply or stl");
|
||||
out->type = b["type"].get<std::string>();
|
||||
if (out->type != "glb" && out->type != "obj" && out->type != "ply" && out->type != "stl")
|
||||
return bad("type", "type '" + out->type + "' is not one this server writes: glb, obj, "
|
||||
"ply or stl");
|
||||
}
|
||||
r->ticket = std::make_shared<gen::ShapeTicket>();
|
||||
out->req = std::move(r);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The ticket's field as a mesh file, once the driver is done with it. */
|
||||
int finish_file(gen::ShapeTicket& t, const gen::ShapeGenInfo& info, const std::string& type,
|
||||
std::string* file, std::string* mime, std::string* why) {
|
||||
if (t.status() < 0) {
|
||||
*why = t.why();
|
||||
return t.status();
|
||||
}
|
||||
int32_t r = 0;
|
||||
std::vector<float> field = t.take_field(&r);
|
||||
gen::ShapeMesh mesh;
|
||||
gen::shape_mesh(field, r, info.bounds, info.level, &mesh);
|
||||
std::vector<float>().swap(field);
|
||||
if (mesh.f.empty()) {
|
||||
*why = "the model's field crosses the surface level nowhere in the grid: the picture made "
|
||||
"no shape";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return gen::shape_export(mesh, type, file, mime, why);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
struct Server::ShapeJob {
|
||||
std::string uid, type;
|
||||
int64_t created_at = 0, done_at = 0;
|
||||
std::shared_ptr<gen::ShapeTicket> ticket;
|
||||
std::thread worker;
|
||||
/* Under Server::shapes_m_ from here on. */
|
||||
bool finished = false, failed = false;
|
||||
std::string file, message;
|
||||
};
|
||||
|
||||
void Server::shape_caps(json& caps, const IShapeGen* gen) {
|
||||
const gen::ShapeGenInfo& info = gen->info();
|
||||
caps["shape_max_steps"] = info.max_steps;
|
||||
caps["shape_resolutions"] = { info.min_resolution, info.max_resolution };
|
||||
caps["shape_formats"] = json::array({ "glb", "obj", "ply", "stl" });
|
||||
}
|
||||
|
||||
HttpResponse Server::handle_shape_generate(const HttpRequest& req) {
|
||||
if (!deps_.shapes)
|
||||
return error_response(err_not_implemented(
|
||||
"/generate requires a 3-D shape model; this one does not make shapes"), req.peer);
|
||||
const gen::ShapeGenInfo& info = deps_.shapes->info();
|
||||
ShapeAsk a;
|
||||
ApiError err;
|
||||
if (read_ask(req, lim_, info, &a, &err) < 0) return error_response(err, req.peer);
|
||||
std::shared_ptr<gen::ShapeTicket> t = a.req->ticket;
|
||||
std::string why;
|
||||
if (const int st = deps_.shapes->submit(std::move(a.req), &why); st < 0)
|
||||
return error_response(st == RAD_E_INVAL ? err_bad("image", why) : err_overloaded(why),
|
||||
req.peer);
|
||||
while (!t->wait(500))
|
||||
if (stopping_.load()) {
|
||||
t->cancel.store(true);
|
||||
return error_response(err_overloaded("the server is stopping"), req.peer);
|
||||
}
|
||||
std::string file, mime;
|
||||
if (const int st = finish_file(*t, info, a.type, &file, &mime, &why); st < 0)
|
||||
return error_response(st == RAD_E_INVAL ? err_bad("image", why) : err_internal(why),
|
||||
req.peer);
|
||||
HttpResponse res;
|
||||
res.content_type = mime;
|
||||
res.body = std::move(file);
|
||||
return res;
|
||||
}
|
||||
|
||||
void Server::shape_work(std::shared_ptr<ShapeJob> j) {
|
||||
const gen::ShapeGenInfo& info = deps_.shapes->info();
|
||||
gen::ShapeTicket& t = *j->ticket;
|
||||
while (!t.wait(500))
|
||||
if (stopping_.load()) {
|
||||
t.cancel.store(true);
|
||||
t.wait(60000);
|
||||
break;
|
||||
}
|
||||
std::string file, mime, why;
|
||||
const int st = t.finished() ? finish_file(t, info, j->type, &file, &mime, &why)
|
||||
: RAD_E_CANCELLED;
|
||||
std::lock_guard<std::mutex> lk(shapes_m_);
|
||||
j->finished = true;
|
||||
j->done_at = unix_now();
|
||||
if (st < 0) {
|
||||
j->failed = true;
|
||||
j->message = why.empty() ? std::string(rad_strerror(st)) : why;
|
||||
} else {
|
||||
j->file = std::move(file);
|
||||
}
|
||||
}
|
||||
|
||||
void Server::sweep_shapes_locked(int64_t now) {
|
||||
for (size_t i = 0; i < shapes_.size();) {
|
||||
ShapeJob& j = *shapes_[i];
|
||||
const bool expired = j.finished && now - j.done_at > opt_.video_ttl_s;
|
||||
if (!expired) { ++i; continue; }
|
||||
if (j.worker.joinable()) j.worker.join();
|
||||
shapes_.erase(shapes_.begin() + (std::ptrdiff_t)i);
|
||||
}
|
||||
/* Past the cap the oldest finished shapes go first. */
|
||||
size_t done = 0;
|
||||
for (const auto& j : shapes_) done += j->finished;
|
||||
const size_t cap = (size_t)std::max<int64_t>(opt_.max_videos, 1);
|
||||
for (size_t i = 0; done > cap && i < shapes_.size();) {
|
||||
if (!shapes_[i]->finished) { ++i; continue; }
|
||||
if (shapes_[i]->worker.joinable()) shapes_[i]->worker.join();
|
||||
shapes_.erase(shapes_.begin() + (std::ptrdiff_t)i);
|
||||
--done;
|
||||
}
|
||||
}
|
||||
|
||||
void Server::stop_shapes() {
|
||||
std::vector<std::shared_ptr<ShapeJob>> all;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(shapes_m_);
|
||||
all = shapes_;
|
||||
}
|
||||
for (auto& j : all) j->ticket->cancel.store(true);
|
||||
for (auto& j : all)
|
||||
if (j->worker.joinable()) j->worker.join();
|
||||
}
|
||||
|
||||
HttpResponse Server::handle_shape_send(const HttpRequest& req) {
|
||||
if (!deps_.shapes)
|
||||
return error_response(err_not_implemented(
|
||||
"/send requires a 3-D shape model; this one does not make shapes"), req.peer);
|
||||
const gen::ShapeGenInfo& info = deps_.shapes->info();
|
||||
ShapeAsk a;
|
||||
ApiError err;
|
||||
if (read_ask(req, lim_, info, &a, &err) < 0) return error_response(err, req.peer);
|
||||
auto j = std::make_shared<ShapeJob>();
|
||||
j->uid = random_id("shape_");
|
||||
j->type = a.type;
|
||||
j->created_at = unix_now();
|
||||
j->ticket = a.req->ticket;
|
||||
std::string why;
|
||||
if (const int st = deps_.shapes->submit(std::move(a.req), &why); st < 0)
|
||||
return error_response(st == RAD_E_INVAL ? err_bad("image", why) : err_overloaded(why),
|
||||
req.peer);
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(shapes_m_);
|
||||
sweep_shapes_locked(unix_now());
|
||||
shapes_.push_back(j);
|
||||
}
|
||||
j->worker = std::thread([this, j] { shape_work(j); });
|
||||
json o;
|
||||
o["uid"] = j->uid;
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
|
||||
HttpResponse Server::handle_shape_status(const HttpRequest& req) {
|
||||
if (!deps_.shapes)
|
||||
return error_response(err_not_implemented(
|
||||
"/status requires a 3-D shape model; this one does not make shapes"), req.peer);
|
||||
const std::string uid = req.param("uid");
|
||||
std::lock_guard<std::mutex> lk(shapes_m_);
|
||||
sweep_shapes_locked(unix_now());
|
||||
for (const auto& j : shapes_) {
|
||||
if (j->uid != uid) continue;
|
||||
json o;
|
||||
if (!j->finished) {
|
||||
o["status"] = "processing";
|
||||
int32_t steps = 0, points = 0;
|
||||
j->ticket->progress_of(&steps, &points);
|
||||
o["steps_done"] = steps;
|
||||
o["steps"] = j->ticket->steps;
|
||||
} else if (j->failed) {
|
||||
o["status"] = "error";
|
||||
o["message"] = j->message;
|
||||
} else {
|
||||
o["status"] = "completed";
|
||||
o["type"] = j->type;
|
||||
o["model_base64"] = base64_encode(j->file.data(), j->file.size());
|
||||
}
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
ApiError e = err_bad("uid", "no shape '" + uid + "'; it may have expired");
|
||||
e.status = 404;
|
||||
e.type = "not_found_error";
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
|
||||
} /* namespace server */
|
||||
} /* namespace rad */
|
||||
@@ -535,7 +535,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
canvas_for(rw, rh, se, info.max_area, info.size_multiple, &W, &H);
|
||||
}
|
||||
if (W % info.size_multiple || H % info.size_multiple || W < info.min_side ||
|
||||
H < info.min_side || W * H > info.max_area ||
|
||||
H < info.min_side || W > info.max_area || H > info.max_area || W * H > info.max_area ||
|
||||
std::max(W, H) > info.max_aspect * std::min(W, H)) {
|
||||
int64_t sw = 0, sh = 0;
|
||||
canvas_for((double)W, (double)H, short_def, info.max_area, info.size_multiple, &sw, &sh);
|
||||
|
||||
Reference in new issue
Block a user