Merge commit '22ff409079' into f-ling32-int

This commit is contained in:
Niko1221 committed 2026-12-03 00:23:37 +01:00
commit 79a36f3f18
6 files changed
+645 -16

No files matched your search

+1 -1
View File
@@ -20,7 +20,7 @@ FW="-framework Metal -framework Foundation"
M=$S/src/ling32/metal
# the MSL sources are embedded in the binary (the CLT have no offline metal compiler: they are compiled at run time); --kernels DIR still overrides
mkdir -p $O/gen
python3 $M/embed_metal.py $O/gen/l32_embedded.inc $M/ling32_core.metal $M/ling32_decode.metal $M/ling32_attn.metal $M/ling32_mtp.metal $M/ling32_mpp.metal
python3 $M/embed_metal.py $O/gen/l32_embedded.inc $M/ling32_core.metal $M/ling32_decode.metal $M/ling32_attn.metal $M/ling32_mtp.metal $M/ling32_mpp.metal $M/ling32_vision.metal
INC="$INC -DL32_EMBED -I$O/gen"
LV=$(python3 "$S/../tools/packaging/ling32/engine_version.py") || exit 1 # the shared engine version: no literal in the sources
clang++ $CXXF $INC -DLING32_VERSION="\"$LV\"" -I$Z $M/ling32_metal_main.cpp $S/src/ling32/ling32_file.cpp $S/src/ling32/ling32_vision.cpp $S/src/artifact/strata_reader.cpp $O/zstd/*.o $O/mtl_rt.o $FW -lpthread -o $O/ling32-metal
+57 -7
View File
@@ -1107,7 +1107,7 @@ static std::string kernels_dir(const std::string& req) { return req; }
#endif
// --mm-runs FILE [--vision V]: a batch of picture / text prompts in ONE process (the model is loaded once), the format of the CUDA program's --mm-runs (phaseA-tests/ling32/vision/e2e_batch.tmpl):
// one line per run: tag;ids_file;backend;image[,image...];gen backend: cpu | gpu (both the CPU encoder here) | none (text only); ids_file: comma separated token ids (one <|image_pad|> per
// one line per run: tag;ids_file;backend;image[,image...];gen backend: cpu | gpu (gpu: the Metal encoder when there is one; cpu: the CPU encoder) | none (text only); ids_file: comma separated token ids (one <|image_pad|> per
// picture, or the full runs); greedy decoding, stops on the end tokens. Prints RUN ... / GEN tag: ids / MARGIN tag: top-1 minus top-2 logit of every step / LOGITS tag: hash of the
// last prompt row's logits (bit patterns: equal hashes = bit-identical logits, the text-only check with and without --vision)
static int run_mm_batch(Engine& E, const Opts& o, l32m_vis::VisionRun* vr, std::string& err) {
@@ -1146,9 +1146,10 @@ static int run_mm_batch(Engine& E, const Opts& o, l32m_vis::VisionRun* vr, std::
}
} else {
if (!vr) { err = "pictures need --vision FILE"; return 1; }
vr->force_cpu(f[2] == "cpu");
if (!l32m_vis::build_mm_prompt(*vr, vo, ids, D, mp, err, false)) return 1;
t_vis = now_s() - t0;
std::printf("RUN %s: %zu pictures, encoder cpu, %zu prompt tokens, pictures ready in %.2f s\n", tag.c_str(), vo.images.size(), mp.ids.size(), t_vis);
std::printf("RUN %s: %zu pictures, encoder %s, %zu prompt tokens, pictures ready in %.2f s\n", tag.c_str(), vo.images.size(), (f[2] == "cpu" ? "cpu" : vr->backend()).c_str(), mp.ids.size(), t_vis);
if (!l32m_vis::prefill_mm(E, o.chunk, mp, err)) return 1;
}
const double t_pre = now_s() - t0;
@@ -1227,7 +1228,8 @@ static int cmd_export_tokenizer(const std::string& file, const std::string& dir)
static int cmd_vision_encode(int argc, char** argv) {
VisionRunOpts vo;
vo.file = argv[2];
std::string out;
std::string out, kernels_arg;
bool compare = false, prof = false;
for (int i = 3; i < argc; ++i) {
const std::string a = argv[i];
auto nx = [&]() -> std::string { return i + 1 < argc ? argv[++i] : std::string(); };
@@ -1235,13 +1237,55 @@ static int cmd_vision_encode(int argc, char** argv) {
else if (a == "--vision-threads") vo.threads = std::atoi(nx().c_str());
else if (a == "--vision-max-pixels") vo.max_pixels = std::atoll(nx().c_str());
else if (a == "--out") out = nx();
else if (a == "--compare") compare = true;
else if (a == "--prof") prof = true;
else if (a == "--kernels") kernels_arg = nx();
else vo.images.push_back(a);
}
std::string err;
l32m_vis::VisionRun vr(vo);
std::unique_ptr<mtl::Context> cxp;
std::string kdir;
if (vo.backend != "cpu") { cxp.reset(new mtl::Context); kdir = kernels_dir(kernels_arg); }
l32m_vis::VisionRun vr(vo, cxp.get(), kdir);
const double t_load = now_s();
if (!vr.init(err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
std::printf("encoder: cpu (weights read in %.2f s)\n", now_s() - t_load);
std::printf("encoder: %s (config read in %.2f s)\n", vr.backend().c_str(), now_s() - t_load);
if (prof && vr.gpu()) vr.gpu()->set_prof(true); // GPU time per kernel of every picture (stderr)
if (compare) { // the Metal encoder against the CPU one on the same pictures: relative L2 error of the residual stream after the patch embedding, blocks 0 / 13 / 26, the merger norm and the output
if (!vr.gpu()) { std::fprintf(stderr, "strata-ling32: --compare needs the Metal encoder\n"); return 1; }
VisionWeights W;
if (!W.load(vo.file, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
VisionCfg c = W.c;
if (vo.max_pixels > 0) c.max_pixels = std::min<int64_t>(c.max_pixels, vo.max_pixels);
for (const std::string& img : vo.images) {
PreparedImage im;
if (!vision_prepare_file(c, img, im, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
VisionCheckpoints cc, cg;
std::vector<float> ec, eg;
double t0 = now_s();
if (!vision_encode_cpu(W, im, ec, err, vo.threads, &cc)) { std::fprintf(stderr, "strata-ling32: cpu: %s\n", err.c_str()); return 1; }
const double t_cpu = now_s() - t0;
for (int rep = 0; rep < 2; ++rep) { // the first call loads the weights and compiles the kernels
t0 = now_s();
if (!vr.gpu()->encode(im, eg, err, &cg)) { std::fprintf(stderr, "strata-ling32: gpu: %s\n", err.c_str()); return 1; }
std::printf("%s: %d patches, gpu call %d: %.0f ms wall (gpu %.0f ms, host prep %.0f ms); cpu %.0f ms\n", img.c_str(), im.gh * im.gw, rep + 1, (now_s() - t0) * 1000.0, vr.gpu()->last_gpu_ms(), vr.gpu()->last_host_ms(), t_cpu * 1000.0);
}
auto rel = [](const char* nm, const std::vector<float>& a, const std::vector<float>& b) {
double d = 0, n = 0, mx = 0;
const size_t m = std::min(a.size(), b.size());
for (size_t i = 0; i < m; ++i) { const double e = double(a[i]) - double(b[i]); d += e * e; n += double(b[i]) * double(b[i]); mx = std::max(mx, std::fabs(e)); }
std::printf(" %-8s rel L2 %.3e max abs %.3e (%zu values%s)\n", nm, std::sqrt(d / std::max(n, 1e-30)), mx, m, a.size() != b.size() ? ", SIZES DIFFER" : "");
};
rel("embed", cg.embed, cc.embed);
rel("blk0", cg.blk0, cc.blk0);
rel("blk13", cg.blk13, cc.blk13);
rel("blk26", cg.blk26, cc.blk26);
rel("merged", cg.merged, cc.merged);
rel("out", eg, ec);
if (!out.empty()) { std::ofstream(out + ".gpu.f32", std::ios::binary).write(reinterpret_cast<const char*>(eg.data()), std::streamsize(eg.size() * 4)); std::ofstream(out + ".cpu.f32", std::ios::binary).write(reinterpret_cast<const char*>(ec.data()), std::streamsize(ec.size() * 4)); }
}
return 0;
}
std::ofstream of;
if (!out.empty()) of.open(out, std::ios::binary);
VisionCfg c = vr.cfg();
@@ -1479,10 +1523,10 @@ int main(int argc, char** argv) {
}
std::unique_ptr<l32m_vis::VisionRun> vrun; // pictures: the CPU encoder, its weights (829 MiB) read before the model so that a bad file fails fast
if (!o.vis.file.empty() || !o.vis.images.empty()) {
vrun.reset(new l32m_vis::VisionRun(o.vis));
vrun.reset(new l32m_vis::VisionRun(o.vis, &cx, o.kernels));
const double tv = now_s();
if (!vrun->init(err)) { std::fprintf(stderr, "vision: %s\n", err.c_str()); return 1; }
std::fprintf(stderr, "ling32-metal: picture encoder: cpu, weights read in %.2f s\n", now_s() - tv);
std::fprintf(stderr, "ling32-metal: picture encoder: %s, config read in %.2f s\n", vrun->backend().c_str(), now_s() - tv);
}
Model m;
g_ws_gib = cx.recommended_working_set() / 1073741824.0;
@@ -1512,6 +1556,12 @@ int main(int argc, char** argv) {
E.reset();
std::fprintf(stderr, "ling32-metal: first command buffer (wiring) %.1f s\n", now_s() - tw);
}
if (o.serve && vrun && vrun->gpu()) { // the Metal picture encoder: weights on the GPU and kernels compiled before the first request
std::string verr;
const double tv = now_s();
if (vrun->gpu()->preload(verr)) std::fprintf(stderr, "ling32-metal: picture encoder ready in %.2f s, rss %.1f GiB\n", now_s() - tv, rss_gib());
else std::fprintf(stderr, "ling32-metal: picture encoder (Metal): %s; pictures use the CPU encoder\n", verr.c_str());
}
g_loading = false; // the model and the engine buffers are made
if (o.serve) { // the protocol goes to a dup of stdout; everything else printed to stdout is moved to stderr
l32m_serve::g_out = fdopen(dup(1), "w");
@@ -3,9 +3,11 @@
// without its GPU encoder. Header only (included by ling32_metal_serve.hpp and ling32_metal_main.cpp).
#pragma once
#include "ling32_metal_vision_gpu.hpp"
#include "strata/ling32/ling32_vision.hpp"
#include <algorithm>
#include <memory>
#include <chrono>
#include <cmath>
#include <cstdint>
@@ -30,27 +32,53 @@ struct MmChunk {
const int* mpos = nullptr;
};
// The picture encoder object: the Metal GPU encoder (ling32_metal_vision_gpu.hpp) when a Metal context is given and the backend is auto or gpu, else the CPU encoder; a GPU encoder that cannot run
// a picture (memory, a kernel that does not compile) falls back to the CPU one for that picture, with one log line.
class VisionRun {
public:
explicit VisionRun(const VisionRunOpts& o) : o_(o) {}
const VisionCfg& cfg() const { return w_.c; }
std::string backend() const { return "cpu"; } // the only encoder of this engine
explicit VisionRun(const VisionRunOpts& o, mtl::Context* cx = nullptr, const std::string& kernel_dir = "") : o_(o), cx_(cx), kdir_(kernel_dir) {}
const VisionCfg& cfg() const { return cfg_; }
std::string backend() const { return backend_; } // "cpu" or "gpu"
bool init(std::string& err) {
if (o_.file.empty()) { err = "pictures need --vision FILE (Ling-3.2-Air-Vision.strata)"; return false; }
if (o_.backend != "auto" && o_.backend != "cpu" && o_.backend != "gpu") { err = "--vision-device must be auto, cpu or gpu"; return false; }
if (o_.backend == "gpu") std::fprintf(stderr, "[vision] --vision-device gpu: the Metal engine has the CPU encoder only, using it\n");
return w_.load(o_.file, err);
backend_ = (o_.backend == "cpu" || !cx_) ? "cpu" : "gpu";
if (o_.backend == "gpu" && !cx_) std::fprintf(stderr, "[vision] --vision-device gpu: no Metal context here, using the CPU encoder\n");
if (!w_.load(o_.file, err)) return false; // the config; the CPU weights stay only when the CPU encoder is the one in use (a fallback reloads them)
cfg_ = w_.c;
if (backend_ == "gpu") {
gpu_.reset(new VisionGpu(*cx_, o_.file, kdir_));
w_ = VisionWeights{};
w_.c = cfg_;
}
return true;
}
VisionGpu* gpu() { return gpu_.get(); }
void force_cpu(bool v) { force_cpu_ = v; } // tests: use the CPU encoder although the GPU one exists
bool encode(const PreparedImage& im, std::vector<float>& out, std::string& err, double* ms = nullptr) {
const auto t0 = std::chrono::steady_clock::now();
const bool ok = strata::ling32::vision_encode_cpu(w_, im, out, err, o_.threads);
bool ok = false;
if (gpu_ && !force_cpu_) {
std::string gerr;
ok = gpu_->encode(im, out, gerr);
if (!ok) std::fprintf(stderr, "[vision] Metal encoder: %s; using the CPU encoder for this picture\n", gerr.c_str());
}
if (!ok) {
if (w_.blk.empty() && !w_.load(o_.file, err)) return false;
ok = strata::ling32::vision_encode_cpu(w_, im, out, err, o_.threads);
}
if (ms) *ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
return ok;
}
private:
VisionRunOpts o_;
mtl::Context* cx_;
bool force_cpu_ = false;
std::string kdir_, backend_ = "cpu";
VisionCfg cfg_;
VisionWeights w_;
std::unique_ptr<VisionGpu> gpu_;
};
struct MmPrompt {
@@ -113,7 +141,7 @@ inline bool build_mm_prompt(VisionRun& vr, const VisionRunOpts& o, const std::ve
for (float v : e)
if (!std::isfinite(v)) { err = "NaN / Inf in the picture embeddings of " + o.images[k]; return false; }
std::copy(e.begin(), e.end(), mp.emb.begin() + static_cast<std::ptrdiff_t>(at * D));
if (log) std::printf("picture %zu: %s -> %dx%d, %d embeddings, cpu encoder %.0f ms\n", k + 1, o.images[k].c_str(), ims[k].w, ims[k].h, tok[k], ms);
if (log) std::printf("picture %zu: %s -> %dx%d, %d embeddings, %s encoder %.0f ms\n", k + 1, o.images[k].c_str(), ims[k].w, ims[k].h, tok[k], vr.backend().c_str(), ms);
at += static_cast<size_t>(tok[k]);
i += static_cast<size_t>(tok[k]);
++k;
@@ -0,0 +1,311 @@
// ling32_metal_vision_gpu.hpp - the picture encoder of the Ling-3.2-Air Vision shard on the Metal GPU (kernels: ling32_vision.metal).
//
// The weights (BF16 in the file) are widened to fp16 once, on the first picture, and stay resident (about 0.83 GiB); the activations of a picture are allocated for the call and freed after it.
// Activations are fp32 between the blocks; every matrix product splits its activation operand in two fp16 numbers (hi, lo) and runs on the matrix unit (see the kernel file).
// The CPU encoder (ling32_vision.cpp) stays the reference and the fallback: VisionRun uses it when this one cannot run.
#pragma once
#include "mtl_rt.h"
#include "strata/ling32/ling32_vision.hpp"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstdlib>
#include <cstring>
#include <map>
#include <string>
#include <thread>
#include <vector>
namespace l32m_vis {
class VisionGpu {
public:
VisionGpu(mtl::Context& cx, const std::string& file, const std::string& kernel_dir) : cx_(cx), file_(file), kdir_(kernel_dir) {}
~VisionGpu() { unload(); }
bool loaded() const { return loaded_; }
void set_prof(bool v) { prof_ = v; }
double last_gpu_ms() const { return last_gpu_ms_; }
double last_host_ms() const { return last_host_ms_; }
// out = [tokens, out_dim] fp32. ck (optional, debug): embed (after the patch embedding), blk0, blk13, blk26 (residual stream after those blocks), merged (the merger's layer norm output).
bool encode(const strata::ling32::PreparedImage& img, std::vector<float>& out, std::string& err, strata::ling32::VisionCheckpoints* ck = nullptr) {
using namespace strata::ling32;
if (!ensure_loaded(err)) return false;
const auto th0 = std::chrono::steady_clock::now();
const VisionCfg& c = cfg_;
const int S = img.gh * img.gw, D = c.hidden, H = c.heads, hd = c.head_dim(), F = c.ffn, PV = c.patch_vals(), gh = img.gh, gw = img.gw, M2 = c.merge;
if (img.pix.empty() || gh % M2 || gw % M2) { err = "vision: empty or misaligned picture"; return false; }
if (D != 1152 || H != 16 || hd != 72 || F != 4304 || PV != 1536 || c.out_dim != 2560) { err = "vision (Metal): the kernels are made for the Ling-3.2-Air tower (1152 / 16 x 72 / 4304)"; return false; }
constexpr int QB = 256, HDP = 80, FP = 4352;
const int Sp = (S + QB - 1) / QB * QB, T = S / (M2 * M2), Tp = (T + 63) / 64 * 64, nqb = (S + QB - 1) / QB, OD = c.out_dim;
// memory: refuse (the caller falls back to the CPU encoder) instead of letting an allocation end the process
const double need = (double(Sp) * (D * 4.0 + 4.0 * D + 3.0 * D * 4 + 2.0 * PV * 2 + 2.0 * 2 * D + 2.0 * 2 * FP) + 2.0 * 2 * H * double(Sp) * HDP * 2 * 1.5 + 2.0 * H * QB * double(Sp) * (4 + 2 + 2) + double(Tp) * OD * 8.0);
const double room = double(cx_.recommended_working_set()) - double(cx_.allocated());
if (need > room * 0.9) { err = "vision (Metal): the picture needs about " + std::to_string(int(need / 1048576)) + " MiB of GPU memory, " + std::to_string(int(room / 1048576)) + " MiB are free"; return false; }
auto A = [&](size_t bytes) { return cx_.alloc(bytes); };
mtl::Buffer x = A(size_t(Sp) * D * 4), hH = A(size_t(Sp) * D * 2), hL = A(size_t(Sp) * D * 2), qkv = A(size_t(Sp) * 3 * D * 4);
mtl::Buffer pixH = A(size_t(Sp) * PV * 2), pixL = A(size_t(Sp) * PV * 2);
mtl::Buffer qh = A(size_t(H) * Sp * HDP * 2), ql = A(size_t(H) * Sp * HDP * 2), kh = A(size_t(H) * Sp * HDP * 2), kl = A(size_t(H) * Sp * HDP * 2), vh = A(size_t(H) * HDP * Sp * 2), vl = A(size_t(H) * HDP * Sp * 2);
mtl::Buffer sc = A(size_t(H) * QB * Sp * 4), ph = A(size_t(H) * QB * Sp * 2), pl = A(size_t(H) * QB * Sp * 2), inv = A(size_t(H) * QB * 4);
mtl::Buffer aH = A(size_t(Sp) * D * 2), aL = A(size_t(Sp) * D * 2), mH = A(size_t(Sp) * FP * 2), mL = A(size_t(Sp) * FP * 2);
mtl::Buffer lpH = A(size_t(Tp) * OD * 2), lpL = A(size_t(Tp) * OD * 2), outb = A(size_t(Tp) * OD * 4);
mtl::Buffer csb, snb, prb, pcb;
mtl::Buffer ck_embed, ck_b0, ck_b13, ck_b26;
auto release = [&] { for (mtl::Buffer* b : {&x, &hH, &hL, &qkv, &pixH, &pixL, &qh, &ql, &kh, &kl, &vh, &vl, &sc, &ph, &pl, &inv, &aH, &aL, &mH, &mL, &lpH, &lpL, &outb, &csb, &snb, &prb, &pcb, &ck_embed, &ck_b0, &ck_b13, &ck_b26}) if (b->handle) cx_.free(*b); };
// ---- host side: patch pixels as halves, the position grid added to the residual stream, the rope tables and the patch -> (row, column) maps
{
_Float16* pxh = static_cast<_Float16*>(pixH.ptr);
_Float16* pxl = static_cast<_Float16*>(pixL.ptr);
const float* pix = img.pix.data();
parallel_rows(S, [&](int r) {
for (int i = 0; i < PV; ++i) {
const float v = pix[size_t(r) * PV + i];
const _Float16 h = static_cast<_Float16>(v);
pxh[size_t(r) * PV + i] = h;
pxl[size_t(r) * PV + i] = static_cast<_Float16>(v - static_cast<float>(h));
}
});
const int side = c.pos_side;
auto lin = [&](int i, int n, double& idx, int& fl, int& ce, double& d) {
idx = n > 1 ? i * (static_cast<double>(side - 1) / (n - 1)) : 0.0;
fl = static_cast<int>(idx);
ce = std::min(fl + 1, side - 1);
d = idx - fl;
};
float* xp = x.as<float>();
const int nbr = gh / M2, nbc = gw / M2;
parallel_rows(nbr * nbc, [&](int blk) {
const int br = blk / nbc, bc = blk % nbc;
for (int dy = 0; dy < M2; ++dy)
for (int dx = 0; dx < M2; ++dx) {
const int row = br * M2 + dy, col = bc * M2 + dx;
double hi, wi, dh, dw;
int hf, hc, wf, wc;
lin(row, gh, hi, hf, hc, dh);
lin(col, gw, wi, wf, wc, dw);
const float w11 = static_cast<float>(dh * dw), w10 = static_cast<float>(dh - dh * dw), w01 = static_cast<float>(dw - dh * dw), w00 = static_cast<float>(1 - dh - (dw - dh * dw));
const uint16_t* p00 = &pos_[(static_cast<size_t>(hf) * side + wf) * D];
const uint16_t* p01 = &pos_[(static_cast<size_t>(hf) * side + wc) * D];
const uint16_t* p10 = &pos_[(static_cast<size_t>(hc) * side + wf) * D];
const uint16_t* p11 = &pos_[(static_cast<size_t>(hc) * side + wc) * D];
float* o = xp + ((static_cast<size_t>(br) * nbc + bc) * M2 * M2 + static_cast<size_t>(dy) * M2 + dx) * D;
for (int i = 0; i < D; ++i) o[i] = bf16f(p00[i]) * w00 + bf16f(p01[i]) * w01 + bf16f(p10[i]) * w10 + bf16f(p11[i]) * w11;
}
});
const int half = hd / 2, nf = half / 2;
const int np = std::max(gh, gw);
csb = A(size_t(np) * nf * 4);
snb = A(size_t(np) * nf * 4);
prb = A(size_t(S) * 4);
pcb = A(size_t(S) * 4);
for (int p = 0; p < np; ++p)
for (int f = 0; f < nf; ++f) {
const double iv = 1.0 / std::pow(10000.0, static_cast<double>(2 * f) / half);
csb.as<float>()[size_t(p) * nf + f] = static_cast<float>(std::cos(p * iv));
snb.as<float>()[size_t(p) * nf + f] = static_cast<float>(std::sin(p * iv));
}
for (int br = 0; br < gh / M2; ++br)
for (int bc = 0; bc < gw / M2; ++bc)
for (int dy = 0; dy < M2; ++dy)
for (int dx = 0; dx < M2; ++dx) {
const size_t i = ((static_cast<size_t>(br) * (gw / M2) + bc) * M2 + dy) * M2 + dx;
prb.as<int>()[i] = br * M2 + dy;
pcb.as<int>()[i] = bc * M2 + dx;
}
}
if (ck) {
ck_embed = A(size_t(S) * D * 4); ck_b0 = A(size_t(S) * D * 4); ck_b13 = A(size_t(S) * D * 4); ck_b26 = A(size_t(S) * D * 4);
}
// ---- the tape
std::vector<mtl::Dispatch> tp;
auto B = [](const mtl::Buffer& b, size_t off = 0) { return mtl::Arg::B(b, off); };
auto I = [](int v) { return mtl::Arg::V<int>(v); };
auto add = [&](const mtl::Pipeline& p, std::vector<mtl::Arg> args, uint32_t gx, uint32_t gy, uint32_t gz, uint32_t tgx) {
mtl::Dispatch d;
d.p = &p;
d.args = std::move(args);
d.grid[0] = gx; d.grid[1] = gy; d.grid[2] = gz;
d.tg[0] = tgx;
tp.push_back(std::move(d));
};
// C / residual / GELU outputs of X . W^T: mode 0 store, 1 add to Cf, 2 / 3 GELU into halves
auto gemm = [&](int mode, const mtl::Buffer& xh, const mtl::Buffer& xl, const mtl::Buffer& W, const mtl::Buffer& bias, const mtl::Buffer& Cf, const mtl::Buffer& Oh, const mtl::Buffer& Ol, int K, int N, int M, int ldo) {
add(P("vit_gemm_64_64_" + std::to_string(mode)), {B(xh), B(xl), B(W), B(bias), B(Cf), B(Oh), B(Ol), I(K), I(N), I(M), I(ldo)}, (N + 63) / 64, (M + 63) / 64, 1, 128);
};
const float eps = c.eps;
auto ln = [&](const mtl::Buffer& w, const mtl::Buffer& b, int rows) { add(P("vit_ln"), {B(x), B(w), B(b), B(hH), B(hL), mtl::Arg::V<float>(eps)}, rows, 1, 1, 256); };
auto copy = [&](const mtl::Buffer& dst) { add(P("vit_copy"), {B(x), B(dst), I(S * D)}, (S * D + 255) / 256, 1, 1, 256); };
const mtl::Buffer dummy = hH; // an output the mode ignores
gemm(1, pixH, pixL, patch_w_, patch_b_, x, dummy, dummy, PV, D, S, D); // x holds the position grid: x += pixels . W^T + b
if (ck) copy(ck_embed);
const float scale = 1.0f / std::sqrt(static_cast<float>(hd));
for (int il = 0; il < c.depth; ++il) {
const Blk& b = blk_[size_t(il)];
ln(b.n1w, b.n1b, S);
gemm(0, hH, hL, b.qkv_w, b.qkv_b, qkv, dummy, dummy, D, 3 * D, S, 3 * D);
add(P("vit_qkv_prep"), {B(qkv), B(csb), B(snb), B(prb), B(pcb), B(qh), B(ql), B(kh), B(kl), B(vh), B(vl), I(Sp)}, S, 1, 1, 128);
for (int qb = 0; qb < nqb; ++qb) {
const int q0 = qb * QB;
add(P("vit_qk_64_64"), {B(qh), B(ql), B(kh), B(kl), B(sc), I(Sp), I(q0), I(QB)}, Sp / 64, QB / 64, H, 128);
add(P("vit_softmax"), {B(sc), B(ph), B(pl), B(inv), I(Sp), I(S), I(QB), mtl::Arg::V<float>(scale)}, QB, H, 1, 256);
add(P("vit_pv_64_80"), {B(ph), B(pl), B(vh), B(vl), B(inv), B(aH), B(aL), I(Sp), I(S), I(q0), I(QB)}, 1, QB / 64, H, 128);
}
gemm(1, aH, aL, b.proj_w, b.proj_b, x, dummy, dummy, D, D, S, D);
ln(b.n2w, b.n2b, S);
gemm(2, hH, hL, b.fc1_w, b.fc1_b, dummy, mH, mL, D, F, S, FP);
gemm(1, mH, mL, b.fc2_w, b.fc2_b, x, dummy, dummy, FP, D, S, D);
if (ck) { if (il == 0) copy(ck_b0); if (il == 13) copy(ck_b13); if (il == 26) copy(ck_b26); }
}
ln(merger_w_, merger_b_, S);
gemm(3, hH, hL, lp0_w_, lp0_b_, dummy, lpH, lpL, 4 * D, OD, T, OD); // [S, 1152] viewed as [T, 4608]
gemm(0, lpH, lpL, lp2_w_, lp2_b_, outb, dummy, dummy, OD, OD, T, OD);
last_host_ms_ = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - th0).count();
last_gpu_ms_ = cx_.run_graph(tp) * 1000.0;
if (prof_) { // GPU time per kernel: the dispatches of one kernel alone (their inputs are whatever the buffers hold now; the times are what counts)
std::map<std::string, std::vector<mtl::Dispatch>> by;
for (const auto& d : tp) by[d.p->name].push_back(d);
for (auto& kv : by) {
double best = 1e9;
for (int r = 0; r < 2; ++r) best = std::min(best, cx_.run_graph(kv.second));
std::fprintf(stderr, "[vision prof] %-18s %5zu dispatches %8.1f ms\n", kv.first.c_str(), kv.second.size(), best * 1000.0);
}
}
out.assign(outb.as<float>(), outb.as<float>() + size_t(T) * OD);
if (ck) {
ck->embed.assign(ck_embed.as<float>(), ck_embed.as<float>() + size_t(S) * D);
ck->blk0.assign(ck_b0.as<float>(), ck_b0.as<float>() + size_t(S) * D);
ck->blk13.assign(ck_b13.as<float>(), ck_b13.as<float>() + size_t(S) * D);
ck->blk26.assign(ck_b26.as<float>(), ck_b26.as<float>() + size_t(S) * D);
ck->merged.resize(size_t(S) * D);
const _Float16* mh = static_cast<const _Float16*>(hH.ptr);
const _Float16* ml = static_cast<const _Float16*>(hL.ptr);
for (size_t i = 0; i < ck->merged.size(); ++i) ck->merged[i] = static_cast<float>(mh[i]) + static_cast<float>(ml[i]);
}
release();
return true;
}
// the weights on the GPU and every pipeline made (a server does this before it says READY: the first picture then pays nothing for it)
bool preload(std::string& err) {
if (!ensure_loaded(err)) return false;
for (const char* n : {"vit_ln", "vit_qkv_prep", "vit_qk_64_64", "vit_softmax", "vit_pv_64_80", "vit_copy", "vit_gemm_64_64_0", "vit_gemm_64_64_1", "vit_gemm_64_64_2", "vit_gemm_64_64_3"}) P(n);
return true;
}
void unload() {
if (!loaded_) return;
for (Blk& b : blk_) for (mtl::Buffer* p : {&b.n1w, &b.n1b, &b.n2w, &b.n2b, &b.qkv_b, &b.proj_b, &b.fc1_b, &b.fc2_b, &b.qkv_w, &b.proj_w, &b.fc1_w, &b.fc2_w}) if (p->handle) cx_.free(*p);
for (mtl::Buffer* p : {&patch_w_, &patch_b_, &merger_w_, &merger_b_, &lp0_w_, &lp0_b_, &lp2_w_, &lp2_b_}) if (p->handle) cx_.free(*p);
blk_.clear();
pos_.clear();
loaded_ = false;
}
private:
struct Blk {
mtl::Buffer n1w, n1b, n2w, n2b, qkv_b, proj_b, fc1_b, fc2_b; // fp32 (fc1_b padded to 4352)
mtl::Buffer qkv_w, proj_w, fc1_w, fc2_w; // fp16 [N][K]; fc1: N padded to 4352 rows, fc2: K padded to 4352 columns (zeros)
};
static float bf16f(uint16_t v) {
const uint32_t u = static_cast<uint32_t>(v) << 16;
float f;
std::memcpy(&f, &u, 4);
return f;
}
template <class F>
static void parallel_rows(int n, F&& fn) {
const int nt = static_cast<int>(std::max(1u, std::min(16u, std::thread::hardware_concurrency())));
std::vector<std::thread> th;
for (int t = 0; t < nt; ++t)
th.emplace_back([&, t] { for (int i = t; i < n; i += nt) fn(i); });
for (auto& x : th) x.join();
}
const mtl::Pipeline& P(const std::string& name) {
auto it = pipes_.find(name);
if (it == pipes_.end()) it = pipes_.emplace(name, cx_.pipeline(lib_, name)).first;
return it->second;
}
// fp32 vector -> buffer
mtl::Buffer fbuf(const std::vector<float>& v, size_t pad_to = 0) {
mtl::Buffer b = cx_.alloc(std::max(v.size(), pad_to) * 4);
std::memcpy(b.ptr, v.data(), v.size() * 4);
return b;
}
// BF16 [rows][cols] -> fp16 buffer [rows_pad][cols_pad] (zero padding)
mtl::Buffer wbuf(const std::vector<uint16_t>& w, int rows, int cols, int rows_pad, int cols_pad) {
mtl::Buffer b = cx_.alloc(size_t(rows_pad) * cols_pad * 2);
_Float16* d = static_cast<_Float16*>(b.ptr);
parallel_rows(rows, [&](int r) {
for (int k = 0; k < cols; ++k) d[size_t(r) * cols_pad + k] = static_cast<_Float16>(bf16f(w[size_t(r) * cols + k]));
});
return b;
}
bool ensure_loaded(std::string& err) {
using namespace strata::ling32;
if (loaded_) return true;
const auto t0 = std::chrono::steady_clock::now();
VisionWeights W;
if (!W.load(file_, err)) return false;
cfg_ = W.c;
const VisionCfg& c = cfg_;
if (c.hidden != 1152 || c.heads != 16 || c.ffn != 4304 || c.head_dim() != 72 || c.out_dim != 2560) { err = "vision (Metal): the kernels are made for the Ling-3.2-Air tower"; return false; }
if (lib_ < 0) {
cx_.kernel_dir = kdir_;
cx_.ggml_common_path.clear();
std::string prelude = "#define VIT_D " + std::to_string(c.hidden) + "\n#define VIT_H " + std::to_string(c.heads) + "\n#define VIT_HD " + std::to_string(c.head_dim()) +
"\n#define VIT_HDP 80\n#define VIT_NF " + std::to_string(c.head_dim() / 4) + "\n";
if (const char* t = std::getenv("L32_VIT_TERMS")) // experiments: products per attention matmul, "QK PV" (2 or 3 each)
prelude += std::string("#define VIT_QK_TERMS ") + t[0] + "\n#define VIT_PV_TERMS " + (t[0] && t[1] ? t[1] : '3') + "\n";
std::string why;
lib_ = cx_.compile_try({"ling32_vision.metal"}, prelude, false, &why);
if (lib_ < 0) { err = "vision (Metal): the kernels do not compile: " + why; return false; }
}
const int D = c.hidden, F = c.ffn, FP = 4352;
patch_w_ = wbuf(W.patch_w, D, c.patch_vals(), D, c.patch_vals());
patch_b_ = fbuf(W.patch_b);
merger_w_ = fbuf(W.merger_w);
merger_b_ = fbuf(W.merger_b);
lp0_w_ = wbuf(W.lp0_w, c.out_dim, c.merged_dim(), c.out_dim, c.merged_dim());
lp0_b_ = fbuf(W.lp0_b);
lp2_w_ = wbuf(W.lp2_w, c.out_dim, c.out_dim, c.out_dim, c.out_dim);
lp2_b_ = fbuf(W.lp2_b);
pos_ = W.pos;
blk_.assign(size_t(c.depth), Blk{});
for (int i = 0; i < c.depth; ++i) {
const VisionBlock& s = W.blk[size_t(i)];
Blk& b = blk_[size_t(i)];
b.n1w = fbuf(s.n1w); b.n1b = fbuf(s.n1b); b.n2w = fbuf(s.n2w); b.n2b = fbuf(s.n2b);
b.qkv_b = fbuf(s.qkv_b); b.proj_b = fbuf(s.proj_b); b.fc1_b = fbuf(s.fc1_b, FP); b.fc2_b = fbuf(s.fc2_b);
b.qkv_w = wbuf(s.qkv_w, 3 * D, D, 3 * D, D);
b.proj_w = wbuf(s.proj_w, D, D, D, D);
b.fc1_w = wbuf(s.fc1_w, F, D, FP, D);
b.fc2_w = wbuf(s.fc2_w, D, F, D, FP);
}
loaded_ = true;
std::fprintf(stderr, "[vision] Metal encoder: weights on the GPU in %.2f s\n", std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count());
return true;
}
mtl::Context& cx_;
std::string file_, kdir_;
int lib_ = -1;
bool loaded_ = false, prof_ = false;
double last_gpu_ms_ = 0, last_host_ms_ = 0;
strata::ling32::VisionCfg cfg_;
std::map<std::string, mtl::Pipeline> pipes_;
std::vector<Blk> blk_;
std::vector<uint16_t> pos_;
mtl::Buffer patch_w_, patch_b_, merger_w_, merger_b_, lp0_w_, lp0_b_, lp2_w_, lp2_b_;
};
} // namespace l32m_vis
+240
View File
@@ -0,0 +1,240 @@
// ling32_vision.metal - the Ling-3.2-Air picture encoder (qwen3_moe_vit: 27 blocks, hidden 1152, 16 heads x 72, ffn 4304, merger + 2 linear layers) on the Metal GPU.
// Compiled on its own (ling32_metal_vision_gpu.hpp), with the prelude VIT_D VIT_H VIT_HD VIT_HDP (head dim padded to a multiple of 16) VIT_NF (rope frequencies per axis).
//
// Matrix products run on the M5's neural accelerators (Metal 4 MetalPerformancePrimitives matmul2d). Weights are BF16 widened to fp16 (exact, but for values below 6e-5), activations are
// split in two fp16 numbers (hi, lo = the rounding remainder) and a product costs two or three MMAs with an fp32 accumulator: fp32-like accuracy, the form of the engine's prefill GEMMs.
// X . W^T with W [N][K] fp16 (K a multiple of 64, N rows padded to a multiple of the tile), X as xh / xl [M][K] fp16.
#include <metal_stdlib>
#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h>
using namespace metal;
using namespace mpp::tensor_ops;
// products per matrix multiplication of the attention: 3 = hi.hi + lo.hi + hi.lo (fp32-like), 2 = the second operand in one half only (hi.hi + lo.hi for Q.K^T, hi.hi + hi.lo for P.V)
#ifndef VIT_QK_TERMS
#define VIT_QK_TERMS 3
#endif
#ifndef VIT_PV_TERMS
#define VIT_PV_TERMS 3
#endif
inline float vit_tg_sum(float v, threadgroup float* sm, uint tid, uint n) {
v = simd_sum(v);
if ((tid & 31) == 0) sm[tid >> 5] = v;
threadgroup_barrier(mem_flags::mem_threadgroup);
float t = 0.0f;
for (uint i = 0; i < (n >> 5); ++i) t += sm[i];
threadgroup_barrier(mem_flags::mem_threadgroup);
return t;
}
inline float vit_tg_max(float v, threadgroup float* sm, uint tid, uint n) {
v = simd_max(v);
if ((tid & 31) == 0) sm[tid >> 5] = v;
threadgroup_barrier(mem_flags::mem_threadgroup);
float t = sm[0];
for (uint i = 1; i < (n >> 5); ++i) t = max(t, sm[i]);
threadgroup_barrier(mem_flags::mem_threadgroup);
return t;
}
// erf: Abramowitz-Stegun 7.1.26 refined by one Newton-free rational correction is not needed here; max abs error 1.5e-7 (the GELU outputs are ~1)
inline float vit_erf(float x) {
const float s = x < 0.0f ? -1.0f : 1.0f, a = fabs(x);
const float t = 1.0f / (1.0f + 0.3275911f * a);
const float y = 1.0f - (((((1.061405429f * t - 1.453152027f) * t) + 1.421413741f) * t - 0.284496736f) * t + 0.254829592f) * t * exp(-a * a);
return s * y;
}
inline float vit_gelu_tanh(float x) { return 0.5f * x * (1.0f + precise::tanh(0.7978845608028654f * (x + 0.044715f * x * x * x))); }
inline float vit_gelu_erf(float x) { return 0.5f * x * (1.0f + vit_erf(x * 0.7071067811865476f)); }
// LayerNorm of every row of x [rows][VIT_D] (fp32) into halves (hi, lo). grid rows, 256 threads
kernel void vit_ln(device const float* x [[buffer(0)]], device const float* w [[buffer(1)]], device const float* b [[buffer(2)]], device half* oh [[buffer(3)]], device half* ol [[buffer(4)]],
constant float& eps [[buffer(5)]], uint r [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
threadgroup float sm[8];
device const float* xr = x + (ulong)r * VIT_D;
float s = 0.0f;
for (int i = int(tid); i < VIT_D; i += 256) s += xr[i];
const float mu = vit_tg_sum(s, sm, tid, 256) / float(VIT_D);
float v = 0.0f;
for (int i = int(tid); i < VIT_D; i += 256) { const float d = xr[i] - mu; v += d * d; }
const float inv = 1.0f / sqrt(vit_tg_sum(v, sm, tid, 256) / float(VIT_D) + eps);
for (int i = int(tid); i < VIT_D; i += 256) {
const float y = (xr[i] - mu) * inv * w[i] + b[i];
const half h = half(y);
oh[(ulong)r * VIT_D + i] = h;
ol[(ulong)r * VIT_D + i] = half(y - float(h));
}
}
// C = X . W^T (+ bias) with the epilogue MODE: 0 store fp32 (Cf), 1 Cf += (the residual stream), 2 GELU(tanh) into halves (Oh, Ol), 3 GELU(erf) into halves.
// TERMS 2: Xh.W + Xl.W. grid (ceil(N / TN), ceil(M / TM)), 32 * SG threads. Rows of X beyond M read zeros (padded buffers); outputs only for r < M, c < N. ldo: row stride of the outputs.
template <int TM, int TN, int SG, int MODE>
kernel void vit_gemm(device const half* xh [[buffer(0)]], device const half* xl [[buffer(1)]], device const half* W [[buffer(2)]], device const float* bias [[buffer(3)]],
device float* Cf [[buffer(4)]], device half* Oh [[buffer(5)]], device half* Ol [[buffer(6)]],
constant int& K [[buffer(7)]], constant int& N [[buffer(8)]], constant int& M [[buffer(9)]], constant int& ldo [[buffer(10)]],
uint2 tg [[threadgroup_position_in_grid]]) {
constexpr int TK = 64;
const int n0 = int(tg.x) * TN, row0 = int(tg.y) * TM;
constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate);
matmul2d<desc, execution_simdgroups<SG>> op;
tensor<device half, dextents<int32_t, 2>, tensor_inline> tH((device half*)xh, dextents<int32_t, 2>(K, 1 << 30));
tensor<device half, dextents<int32_t, 2>, tensor_inline> tL((device half*)xl, dextents<int32_t, 2>(K, 1 << 30));
tensor<device half, dextents<int32_t, 2>, tensor_inline> tW((device half*)(W + (ulong)n0 * K), dextents<int32_t, 2>(K, TN));
auto tA0 = tH.template slice<TK, TM>(0, row0);
auto tB0 = tW.template slice<TK, TN>(0, 0);
auto acc = op.template get_destination_cooperative_tensor<decltype(tA0), decltype(tB0), float>();
const uint16_t cap = acc.get_capacity();
for (uint16_t i = 0; i < cap; ++i) acc[i] = 0.0f;
for (int ks = 0; ks < K / TK; ++ks) {
auto tB = tW.template slice<TK, TN>(ks * TK, 0);
auto tA = tH.template slice<TK, TM>(ks * TK, row0);
op.run(tA, tB, acc);
auto tAl = tL.template slice<TK, TM>(ks * TK, row0);
op.run(tAl, tB, acc);
}
for (uint16_t i = 0; i < cap; ++i) {
if (!acc.is_valid_element(i)) continue;
const auto idx = acc.get_multidimensional_index(i);
const int c = n0 + int(idx[0]), r = row0 + int(idx[1]);
if (c >= N || r >= M) continue;
float v = acc[i] + bias[c];
const ulong o = (ulong)r * ldo + c;
if (MODE == 0) Cf[o] = v;
else if (MODE == 1) Cf[o] += v;
else {
v = MODE == 2 ? vit_gelu_tanh(v) : vit_gelu_erf(v);
const half h = half(v);
Oh[o] = h;
Ol[o] = half(v - float(h));
}
}
}
#define VIT_GEMM(TM, TN, SG, MODE) template [[host_name("vit_gemm_" #TM "_" #TN "_" #MODE)]] kernel decltype(vit_gemm<TM, TN, SG, MODE>) vit_gemm<TM, TN, SG, MODE>;
VIT_GEMM(64, 64, 4, 0)
VIT_GEMM(64, 64, 4, 1)
VIT_GEMM(64, 64, 4, 2)
VIT_GEMM(64, 64, 4, 3)
// q / k / v of one patch out of the qkv row [3 * VIT_D] (fp32): the 2-D rope on q and k (row angles on the first VIT_NF dims of a half head, column angles on the next VIT_NF; dim j pairs with j + VIT_HD / 2),
// then q, k as halves hi / lo [head][Sp][VIT_HDP] and v transposed [head][VIT_HDP][Sp]. Padding stays zero (the buffers are zeroed). grid S, 128 threads
kernel void vit_qkv_prep(device const float* qkv [[buffer(0)]], device const float* cs [[buffer(1)]], device const float* sn [[buffer(2)]], device const int* prow [[buffer(3)]], device const int* pcol [[buffer(4)]],
device half* qh [[buffer(5)]], device half* ql [[buffer(6)]], device half* kh [[buffer(7)]], device half* kl [[buffer(8)]], device half* vh [[buffer(9)]], device half* vl [[buffer(10)]],
constant int& Sp [[buffer(11)]], uint s [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
constexpr int HALF = VIT_HD / 2;
device const float* row = qkv + (ulong)s * 3 * VIT_D;
for (int t = int(tid); t < 2 * VIT_H * HALF; t += 128) { // (q | k, head, j < HALF)
const int part = t / (VIT_H * HALF), hh = (t / HALF) % VIT_H, j = t % HALF;
device const float* v = row + part * VIT_D + hh * VIT_HD;
const int pos = j < VIT_NF ? prow[s] : pcol[s];
const float co = cs[pos * VIT_NF + (j % VIT_NF)], si = sn[pos * VIT_NF + (j % VIT_NF)];
const float a = v[j], b = v[j + HALF];
const float o0 = a * co - b * si, o1 = b * co + a * si;
device half* dh = (part == 0 ? qh : kh) + ((ulong)hh * Sp + s) * VIT_HDP;
device half* dl = (part == 0 ? ql : kl) + ((ulong)hh * Sp + s) * VIT_HDP;
const half h0 = half(o0), h1 = half(o1);
dh[j] = h0; dl[j] = half(o0 - float(h0));
dh[j + HALF] = h1; dl[j + HALF] = half(o1 - float(h1));
}
for (int t = int(tid); t < VIT_H * VIT_HD; t += 128) {
const int hh = t / VIT_HD, d = t % VIT_HD;
const float x = row[2 * VIT_D + hh * VIT_HD + d];
const half h = half(x);
vh[((ulong)hh * VIT_HDP + d) * Sp + s] = h;
vl[((ulong)hh * VIT_HDP + d) * Sp + s] = half(x - float(h));
}
}
// scores of one block of QB query rows against all Sp keys: Sc[head][r][key] = Q . K^T (unscaled), Q and K as hi / lo halves: Qh.Kh + Ql.Kh + Qh.Kl.
// grid (Sp / TN, QB / TM, VIT_H), 32 * SG threads. q0: first query row of the block.
template <int TM, int TN, int SG>
kernel void vit_qk(device const half* qh [[buffer(0)]], device const half* ql [[buffer(1)]], device const half* kh [[buffer(2)]], device const half* kl [[buffer(3)]], device float* Sc [[buffer(4)]],
constant int& Sp [[buffer(5)]], constant int& q0 [[buffer(6)]], constant int& QB [[buffer(7)]], uint3 tg [[threadgroup_position_in_grid]]) {
constexpr int TK = VIT_HDP;
const int n0 = int(tg.x) * TN, row0 = int(tg.y) * TM, hh = int(tg.z);
constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate);
matmul2d<desc, execution_simdgroups<SG>> op;
const ulong qo = ((ulong)hh * Sp + q0 + row0) * VIT_HDP, ko = ((ulong)hh * Sp + n0) * VIT_HDP;
tensor<device half, dextents<int32_t, 2>, tensor_inline> tQh((device half*)(qh + qo), dextents<int32_t, 2>(TK, TM));
tensor<device half, dextents<int32_t, 2>, tensor_inline> tQl((device half*)(ql + qo), dextents<int32_t, 2>(TK, TM));
tensor<device half, dextents<int32_t, 2>, tensor_inline> tKh((device half*)(kh + ko), dextents<int32_t, 2>(TK, TN));
tensor<device half, dextents<int32_t, 2>, tensor_inline> tKl((device half*)(kl + ko), dextents<int32_t, 2>(TK, TN));
auto acc = op.template get_destination_cooperative_tensor<decltype(tQh), decltype(tKh), float>();
const uint16_t cap = acc.get_capacity();
for (uint16_t i = 0; i < cap; ++i) acc[i] = 0.0f;
op.run(tQh, tKh, acc);
op.run(tQl, tKh, acc);
if (VIT_QK_TERMS >= 3) op.run(tQh, tKl, acc);
tensor<device float, dextents<int32_t, 2>, tensor_inline> tC(Sc + ((ulong)hh * QB + row0) * Sp, dextents<int32_t, 2>(Sp, TM));
acc.store(tC.slice(n0, 0));
}
template [[host_name("vit_qk_64_64")]] kernel decltype(vit_qk<64, 64, 4>) vit_qk<64, 64, 4>;
// softmax rows (unnormalised): P = exp((s - max) * scale) as halves hi / lo (zero for keys >= S), inv[head][row] = 1 / sum. grid (QB, VIT_H), 256 threads
kernel void vit_softmax(device const float* Sc [[buffer(0)]], device half* ph [[buffer(1)]], device half* pl [[buffer(2)]], device float* inv [[buffer(3)]],
constant int& Sp [[buffer(4)]], constant int& S [[buffer(5)]], constant int& QB [[buffer(6)]], constant float& scale [[buffer(7)]],
uint2 g [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
threadgroup float sm[8];
const ulong base = ((ulong)g.y * QB + g.x) * Sp;
device const float* s = Sc + base;
float mx = -INFINITY;
for (int j = int(tid); j < S; j += 256) mx = max(mx, s[j]);
mx = vit_tg_max(mx, sm, tid, 256);
float sum = 0.0f;
for (int j = int(tid); j < Sp; j += 256) {
float e = 0.0f;
if (j < S) e = exp((s[j] - mx) * scale);
sum += e;
const half h = half(e);
ph[base + j] = h;
if (VIT_PV_TERMS >= 3) pl[base + j] = half(e - float(h));
}
sum = vit_tg_sum(sum, sm, tid, 256);
if (tid == 0) inv[g.y * QB + g.x] = 1.0f / sum;
}
// O = P . V per head for the block of QB query rows: Ph.Vh + Pl.Vh + Ph.Vl (V transposed [head][VIT_HDP][Sp]); the row scale inv is applied and the result goes as halves (hi / lo) into the
// attention output att [Sp][VIT_D] (columns head * VIT_HD ...). grid (1, QB / TM, VIT_H), 32 * SG threads.
template <int TM, int TN, int SG>
kernel void vit_pv(device const half* ph [[buffer(0)]], device const half* pl [[buffer(1)]], device const half* vh [[buffer(2)]], device const half* vl [[buffer(3)]], device const float* inv [[buffer(4)]],
device half* ah [[buffer(5)]], device half* al [[buffer(6)]], constant int& Sp [[buffer(7)]], constant int& S [[buffer(8)]], constant int& q0 [[buffer(9)]], constant int& QB [[buffer(10)]],
uint3 tg [[threadgroup_position_in_grid]]) {
constexpr int TK = 64;
const int row0 = int(tg.y) * TM, hh = int(tg.z);
constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate);
matmul2d<desc, execution_simdgroups<SG>> op;
const ulong po = ((ulong)hh * QB + row0) * Sp, vo = (ulong)hh * VIT_HDP * Sp;
tensor<device half, dextents<int32_t, 2>, tensor_inline> tPh((device half*)(ph + po), dextents<int32_t, 2>(Sp, TM));
tensor<device half, dextents<int32_t, 2>, tensor_inline> tPl((device half*)(pl + po), dextents<int32_t, 2>(Sp, TM));
tensor<device half, dextents<int32_t, 2>, tensor_inline> tVh((device half*)(vh + vo), dextents<int32_t, 2>(Sp, TN));
tensor<device half, dextents<int32_t, 2>, tensor_inline> tVl((device half*)(vl + vo), dextents<int32_t, 2>(Sp, TN));
auto tA0 = tPh.template slice<TK, TM>(0, 0);
auto tB0 = tVh.template slice<TK, TN>(0, 0);
auto acc = op.template get_destination_cooperative_tensor<decltype(tA0), decltype(tB0), float>();
const uint16_t cap = acc.get_capacity();
for (uint16_t i = 0; i < cap; ++i) acc[i] = 0.0f;
for (int ks = 0; ks < Sp / TK; ++ks) {
auto bh = tVh.template slice<TK, TN>(ks * TK, 0);
auto bl = tVl.template slice<TK, TN>(ks * TK, 0);
auto ah_ = tPh.template slice<TK, TM>(ks * TK, row0 * 0);
auto al_ = tPl.template slice<TK, TM>(ks * TK, row0 * 0);
op.run(ah_, bh, acc);
if (VIT_PV_TERMS >= 3) op.run(al_, bh, acc);
op.run(ah_, bl, acc);
}
for (uint16_t i = 0; i < cap; ++i) {
if (!acc.is_valid_element(i)) continue;
const auto idx = acc.get_multidimensional_index(i);
const int c = int(idx[0]), r = row0 + int(idx[1]);
if (c >= VIT_HD || q0 + r >= S) continue;
const float v = acc[i] * inv[hh * QB + r];
const half h = half(v);
const ulong o = (ulong)(q0 + r) * VIT_D + hh * VIT_HD + c;
ah[o] = h;
al[o] = half(v - float(h));
}
}
template [[host_name("vit_pv_64_80")]] kernel decltype(vit_pv<64, 80, 4>) vit_pv<64, 80, 4>;
// debug: copy n floats. grid ceil(n / 256), 256 threads
kernel void vit_copy(device const float* s [[buffer(0)]], device float* d [[buffer(1)]], constant int& n [[buffer(2)]], uint i [[thread_position_in_grid]]) {
if (int(i) < n) d[i] = s[i];
}
+1 -1
View File
@@ -34,7 +34,7 @@ clang++ $CXXF -DSTRATA_GGML_COMMON_DEFAULT='""' -DSTRATA_METAL_KERNELS_DEFAULT='
for f in common/debug common/entropy_common common/error_private common/fse_decompress common/zstd_common common/xxhash decompress/huf_decompress decompress/zstd_ddict decompress/zstd_decompress decompress/zstd_decompress_block; do
clang -O2 $min -DZSTD_DISABLE_ASM=1 -DXXH_NAMESPACE=ZSTD_ -I"$Z" -I"$Z/common" -I"$Z/decompress" -c "$Z/$f.c" -o "$O/zstd/$(basename "$f").o"
done
"$py" "$M/embed_metal.py" "$O/gen/l32_embedded.inc" "$M/ling32_core.metal" "$M/ling32_decode.metal" "$M/ling32_attn.metal" "$M/ling32_mtp.metal" "$M/ling32_mpp.metal"
"$py" "$M/embed_metal.py" "$O/gen/l32_embedded.inc" "$M/ling32_core.metal" "$M/ling32_decode.metal" "$M/ling32_attn.metal" "$M/ling32_mtp.metal" "$M/ling32_mpp.metal" "$M/ling32_vision.metal"
clang++ $CXXF $INC -DL32_EMBED -I"$O/gen" -DLING32_VERSION="\"$ver\"" -DL32_BUILD_ID="\"$id\"" \
"$M/ling32_metal_main.cpp" "$S/src/ling32/ling32_file.cpp" "$S/src/ling32/ling32_vision.cpp" "$S/src/artifact/strata_reader.cpp" "$O"/zstd/*.o "$O/mtl_rt.o" \
-framework Metal -framework Foundation -lpthread -o "$O/strata-ling32"