Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/ggml/blob/master/examples/magika/main.cpp # ggml [Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `ggml / examples / magika / main.cpp` 374 lines ยท 13721 bytes Raw Blame History 1 #include "ggml.h" 2 #include "gguf.h" 3 #include "ggml-cpu.h" 4 #include "ggml-alloc.h" 5 #include "ggml-backend.h" 6 7 #include 8 #include 9 #include 10 #include 11 #include 12 #include 13 14 static const char * magika_labels[] = { 15 "ai", "apk", "appleplist", "asm", "asp", 16 "batch", "bmp", "bzip", "c", "cab", 17 "cat", "chm", "coff", "crx", "cs", 18 "css", "csv", "deb", "dex", "dmg", 19 "doc", "docx", "elf", "emf", "eml", 20 "epub", "flac", "gif", "go", "gzip", 21 "hlp", "html", "ico", "ini", "internetshortcut", 22 "iso", "jar", "java", "javabytecode", "javascript", 23 "jpeg", "json", "latex", "lisp", "lnk", 24 "m3u", "macho", "makefile", "markdown", "mht", 25 "mp3", "mp4", "mscompress", "msi", "mum", 26 "odex", "odp", "ods", "odt", "ogg", 27 "outlook", "pcap", "pdf", "pebin", "pem", 28 "perl", "php", "png", "postscript", "powershell", 29 "ppt", "pptx", "python", "pythonbytecode", "rar", 30 "rdf", "rpm", "rst", "rtf", "ruby", 31 "rust", "scala", "sevenzip", "shell", "smali", 32 "sql", "squashfs", "svg", "swf", "symlinktext", 33 "tar", "tga", "tiff", "torrent", "ttf", 34 "txt", "unknown", "vba", "wav", "webm", 35 "webp", "winregistry", "wmf", "xar", "xls", 36 "xlsb", "xlsx", "xml", "xpi", "xz", 37 "yaml", "zip", "zlibstream" 38 }; 39 40 struct magika_hparams { 41 const int block_size = 4096; 42 const int beg_size = 512; 43 const int mid_size = 512; 44 const int end_size = 512; 45 const int min_file_size_for_dl = 16; 46 const int n_label = 113; 47 const float f_norm_eps = 0.001f; 48 const int padding_token = 256; 49 }; 50 51 struct magika_model { 52 ~magika_model() { 53 ggml_backend_buffer_free(buf_w); 54 ggml_backend_free(backend); 55 ggml_free(ctx_w); 56 } 57 58 magika_hparams hparams; 59 60 struct ggml_tensor * dense_w; 61 struct ggml_tensor * dense_b; 62 63 struct ggml_tensor * layer_norm_gamma; 64 struct ggml_tensor * layer_norm_beta; 65 66 struct ggml_tensor * dense_1_w; 67 struct ggml_tensor * dense_1_b; 68 69 struct ggml_tensor * dense_2_w; 70 struct ggml_tensor * dense_2_b; 71 72 struct ggml_tensor * layer_norm_1_gamma; 73 struct ggml_tensor * layer_norm_1_beta; 74 75 struct ggml_tensor * target_label_w; 76 struct ggml_tensor * target_label_b; 77 78 ggml_backend_t backend = ggml_backend_cpu_init(); 79 ggml_backend_buffer_t buf_w = nullptr; 80 struct ggml_context * ctx_w = nullptr; 81 }; 82 83 struct ggml_tensor * checked_get_tensor(struct ggml_context * ctx, const char * name) { 84 struct ggml_tensor * tensor = ggml_get_tensor(ctx, name); 85 if (!tensor) { 86 fprintf(stderr, "%s: tensor '%s' not found\n", __func__, name); 87 throw std::runtime_error("ggml_get_tensor() failed"); 88 } 89 return tensor; 90 } 91 92 bool magika_model_load(const std::string & fname, magika_model & model) { 93 auto & ctx = model.ctx_w; 94 95 struct gguf_init_params params = { 96 /*.no_alloc =*/ true, 97 /*.ctx =*/ &ctx, 98 }; 99 100 struct gguf_context * ctx_gguf = gguf_init_from_file(fname.c_str(), params); 101 if (!ctx_gguf) { 102 fprintf(stderr, "%s: gguf_init_from_file() failed\n", __func__); 103 return false; 104 } 105 106 model.buf_w = ggml_backend_alloc_ctx_tensors(ctx, model.backend); 107 if (!model.buf_w) { 108 fprintf(stderr, "%s: ggml_backend_alloc_ctx_tensors() failed\n", __func__); 109 gguf_free(ctx_gguf); 110 return false; 111 } 112 113 try { 114 model.dense_w = checked_get_tensor(ctx, "dense/kernel:0"); 115 model.dense_b = checked_get_tensor(ctx, "dense/bias:0"); 116 117 model.layer_norm_gamma = checked_get_tensor(ctx, "layer_normalization/gamma:0"); 118 model.layer_norm_beta = checked_get_tensor(ctx, "layer_normalization/beta:0"); 119 120 model.dense_1_w = checked_get_tensor(ctx, "dense_1/kernel:0"); 121 model.dense_1_b = checked_get_tensor(ctx, "dense_1/bias:0"); 122 123 model.dense_2_w = checked_get_tensor(ctx, "dense_2/kernel:0"); 124 model.dense_2_b = checked_get_tensor(ctx, "dense_2/bias:0"); 125 126 model.layer_norm_1_gamma = checked_get_tensor(ctx, "layer_normalization_1/gamma:0"); 127 model.layer_norm_1_beta = checked_get_tensor(ctx, "layer_normalization_1/beta:0"); 128 129 model.target_label_w = checked_get_tensor(ctx, "target_label/kernel:0"); 130 model.target_label_b = checked_get_tensor(ctx, "target_label/bias:0"); 131 } catch (const std::exception & e) { 132 fprintf(stderr, "%s: %s\n", __func__, e.what()); 133 gguf_free(ctx_gguf); 134 return false; 135 } 136 137 FILE * f = fopen(fname.c_str(), "rb"); 138 if (!f) { 139 fprintf(stderr, "%s: fopen() failed\n", __func__); 140 gguf_free(ctx_gguf); 141 return false; 142 } 143 144 const int n_tensors = gguf_get_n_tensors(ctx_gguf); 145 146 for (int i = 0; i < n_tensors; i++) { 147 const char * name = gguf_get_tensor_name(ctx_gguf, i); 148 struct ggml_tensor * tensor = ggml_get_tensor(ctx, name); 149 size_t offs = gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, i); 150 151 //printf("%-30s: [%3ld, %3ld, %3ld, %3ld] %s\n", 152 // name, 153 // tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3], 154 // ggml_type_name(tensor->type)); 155 156 std::vector buf(ggml_nbytes(tensor)); 157 if (fseek(f, offs, SEEK_SET) != 0) { 158 fprintf(stderr, "%s: fseek() failed\n", __func__); 159 gguf_free(ctx_gguf); 160 fclose(f); 161 return false; 162 } 163 164 if (fread(buf.data(), 1, buf.size(), f) != buf.size()) { 165 fprintf(stderr, "%s: fread() failed\n", __func__); 166 gguf_free(ctx_gguf); 167 fclose(f); 168 return false; 169 } 170 171 ggml_backend_tensor_set(tensor, buf.data(), 0, buf.size()); 172 } 173 174 fclose(f); 175 176 gguf_free(ctx_gguf); 177 178 return true; 179 } 180 181 struct ggml_cgraph * magika_graph( 182 const magika_model & model, 183 const int n_files) { 184 185 const auto & hparams = model.hparams; 186 187 static size_t buf_size = ggml_tensor_overhead()*GGML_DEFAULT_GRAPH_SIZE + ggml_graph_overhead(); 188 static std::vector buf(buf_size); 189 190 struct ggml_init_params params = { 191 /*.mem_size =*/ buf_size, 192 /*.mem_buffer =*/ buf.data(), 193 /*.no_alloc =*/ true, 194 }; 195 196 struct ggml_context * ctx = ggml_init(params); 197 198 struct ggml_cgraph * gf = ggml_new_graph(ctx); 199 200 struct ggml_tensor * input = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, 257, 1536, n_files); // one-hot 201 ggml_set_name(input, "input"); 202 ggml_set_input(input); 203 204 struct ggml_tensor * cur; 205 206 // dense 207 cur = ggml_mul_mat(ctx, model.dense_w, input); 208 cur = ggml_add(ctx, cur, model.dense_b); // [128, 1536, n_files] 209 cur = ggml_gelu(ctx, cur); 210 211 // reshape 212 cur = ggml_reshape_3d(ctx, cur, 512, 384, n_files); // [384, 512, n_files] 213 cur = ggml_cont(ctx, ggml_transpose(ctx, cur)); 214 215 // layer normalization 216 cur = ggml_norm(ctx, cur, hparams.f_norm_eps); 217 cur = ggml_mul(ctx, cur, model.layer_norm_gamma); // [384, 512, n_files] 218 cur = ggml_add(ctx, cur, model.layer_norm_beta); // [384, 512, n_files] 219 220 // dense_1 221 cur = ggml_cont(ctx, ggml_transpose(ctx, cur)); 222 cur = ggml_mul_mat(ctx, model.dense_1_w, cur); 223 cur = ggml_add(ctx, cur, model.dense_1_b); // [256, 384, n_files] 224 cur = ggml_gelu(ctx, cur); 225 226 // dense_2 227 cur = ggml_mul_mat(ctx, model.dense_2_w, cur); 228 cur = ggml_add(ctx, cur, model.dense_2_b); // [256, 384, n_files] 229 cur = ggml_gelu(ctx, cur); 230 231 // global_max_pooling1d 232 cur = ggml_cont(ctx, ggml_transpose(ctx, cur)); // [384, 256, n_files] 233 cur = ggml_pool_1d(ctx, cur, GGML_OP_POOL_MAX, 384, 384, 0); // [1, 256, n_files] 234 cur = ggml_reshape_2d(ctx, cur, 256, n_files); // [256, n_files] 235 236 // layer normalization 1 237 cur = ggml_norm(ctx, cur, hparams.f_norm_eps); 238 cur = ggml_mul(ctx, cur, model.layer_norm_1_gamma); // [256, n_files] 239 cur = ggml_add(ctx, cur, model.layer_norm_1_beta); // [256, n_files] 240 241 // target_label 242 cur = ggml_mul_mat(ctx, model.target_label_w, cur); 243 cur = ggml_add(ctx, cur, model.target_label_b); // [n_label, n_files] 244 cur = ggml_soft_max(ctx, cur); // [n_label, n_files] 245 ggml_set_name(cur, "target_label_probs"); 246 ggml_set_output(cur); 247 248 ggml_build_forward_expand(gf, cur); 249 250 return gf; 251 } 252 253 bool magika_eval( 254 struct magika_model & model, 255 const std::vector & fnames) { 256 257 const auto & hparams = model.hparams; 258 259 static ggml_gallocr_t alloc = ggml_gallocr_new(ggml_backend_get_default_buffer_type(model.backend)); 260 261 struct ggml_cgraph * gf = magika_graph(model, fnames.size()); 262 263 if (!ggml_gallocr_alloc_graph(alloc, gf)) { 264 fprintf(stderr, "%s: ggml_gallocr_alloc_graph() failed\n", __func__); 265 return false; 266 } 267 268 struct ggml_tensor * input = ggml_graph_get_tensor(gf, "input"); 269 270 for (size_t i = 0; i < fnames.size(); i++) { 271 FILE * f = fopen(fnames[i].c_str(), "rb"); 272 if (!f) { 273 fprintf(stderr, "%s: fopen() failed\n", __func__); 274 return false; 275 } 276 fseek(f, 0, SEEK_END); 277 long fsize = ftell(f); 278 279 // the buffer is padded with the padding_token if the file is smaller than the block size 280 std::vector buf(1536, hparams.padding_token); 281 std::vector read_buf(std::max(hparams.beg_size, std::max(hparams.mid_size, hparams.end_size))); 282 283 // read beg 284 fseek(f, 0, SEEK_SET); 285 int n_read = fread(read_buf.data(), 1, hparams.beg_size, f); 286 for (int j = 0; j < n_read; j++) { 287 // pad at the end 288 buf[j] = read_buf[j]; 289 } 290 291 // read mid 292 long mid_offs = std::max(0L, (fsize - hparams.mid_size) / 2); 293 fseek(f, mid_offs, SEEK_SET); 294 n_read = fread(read_buf.data(), 1, hparams.mid_size, f); 295 for (int j = 0; j < n_read; j++) { 296 // pad at both ends 297 long mid_idx = hparams.beg_size + (hparams.mid_size / 2) - n_read / 2 + j; 298 buf[mid_idx] = read_buf[j]; 299 } 300 301 // read end 302 long end_offs = std::max(0L, fsize - hparams.end_size); 303 fseek(f, end_offs, SEEK_SET); 304 n_read = fread(read_buf.data(), 1, hparams.end_size, f); 305 for (int j = 0; j < n_read; j++) { 306 // pad at the beginning 307 int end_idx = hparams.beg_size + hparams.mid_size + hparams.end_size - n_read + j; 308 buf[end_idx] = read_buf[j]; 309 } 310 311 fclose(f); 312 313 const size_t inp_bytes = hparams.beg_size + hparams.mid_size + hparams.end_size; 314 315 // convert to one-hot 316 std::vector one_hot(257*inp_bytes); 317 for (size_t j = 0; j < inp_bytes; j++) { 318 one_hot[257*j + buf[j]] = 1.0f; 319 } 320 321 ggml_backend_tensor_set(input, one_hot.data(), 257*inp_bytes*i*sizeof(float), 257*inp_bytes*sizeof(float)); 322 } 323 324 if (ggml_backend_graph_compute(model.backend, gf) != GGML_STATUS_SUCCESS) { 325 fprintf(stderr, "%s: ggml_backend_graph_compute() failed\n", __func__); 326 return false; 327 } 328 329 struct ggml_tensor * target_label_probs = ggml_graph_get_tensor(gf, "target_label_probs"); 330 331 // print probabilities for the top labels of each file 332 for (size_t i = 0; i < fnames.size(); i++) { 333 std::vector probs(hparams.n_label); 334 ggml_backend_tensor_get(target_label_probs, probs.data(), hparams.n_label*i*sizeof(float), hparams.n_label*sizeof(float)); 335 336 // sort the probabilities 337 std::vector idx(hparams.n_label); 338 std::iota(idx.begin(), idx.end(), 0); 339 std::sort(idx.begin(), idx.end(), [&probs](int i1, int i2) { return probs[i1] > probs[i2]; }); 340 341 // print the top labels 342 const int top_n = 5; 343 printf("%-30s: ", fnames[i].c_str()); 344 for (int j = 0; j < top_n; j++) { 345 printf("%s (%.2f%%) ", magika_labels[idx[j]], probs[idx[j]]*100); 346 } 347 printf("\n"); 348 } 349 350 return true; 351 } 352 353 int main(int argc, const char ** argv) { 354 if (argc < 3) { 355 fprintf(stderr, "usage: %s [ ...]\n", argv[0]); 356 return 1; 357 } 358 359 const char * model_fname = argv[1]; 360 std::vector fnames; 361 for (int i = 2; i < argc; i++) { 362 fnames.push_back(argv[i]); 363 } 364 365 magika_model model; 366 if (!magika_model_load(model_fname, model)) { 367 fprintf(stderr, "magika_model_load() failed\n"); 368 return 1; 369 } 370 371 magika_eval(model, fnames); 372 373 return 0; 374 }