compile_efficientnet.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from pathlib import Path
  2. from extra.models.efficientnet import EfficientNet
  3. from tinygrad.tensor import Tensor
  4. from tinygrad.nn.state import safe_save
  5. from extra.export_model import export_model
  6. from tinygrad.helpers import getenv, fetch
  7. import ast
  8. if __name__ == "__main__":
  9. model = EfficientNet(0)
  10. model.load_from_pretrained()
  11. mode = "clang" if getenv("CLANG", "") != "" else "webgpu" if getenv("WEBGPU", "") != "" else "webgl" if getenv("WEBGL", "") != "" else ""
  12. prg, inp_sizes, out_sizes, state = export_model(model, mode, Tensor.randn(1,3,224,224))
  13. dirname = Path(__file__).parent
  14. if getenv("CLANG", "") == "":
  15. safe_save(state, (dirname / "net.safetensors").as_posix())
  16. ext = "js" if getenv("WEBGPU", "") != "" or getenv("WEBGL", "") != "" else "json"
  17. with open(dirname / f"net.{ext}", "w") as text_file:
  18. text_file.write(prg)
  19. else:
  20. cprog = [prg]
  21. # image library!
  22. cprog += ["#define STB_IMAGE_IMPLEMENTATION", fetch("https://raw.githubusercontent.com/nothings/stb/master/stb_image.h").read_text().replace("half", "_half")]
  23. # imagenet labels, move to datasets?
  24. lbls = ast.literal_eval(fetch("https://gist.githubusercontent.com/yrevar/942d3a0ac09ec9e5eb3a/raw/238f720ff059c1f82f368259d1ca4ffa5dd8f9f5/imagenet1000_clsidx_to_labels.txt").read_text())
  25. lbls = ['"'+lbls[i]+'"' for i in range(1000)]
  26. inputs = "\n".join([f"float {inp}[{inp_size}];" for inp,inp_size in inp_sizes.items()])
  27. outputs = "\n".join([f"float {out}[{out_size}];" for out,out_size in out_sizes.items()])
  28. cprog.append(f"char *lbls[] = {{{','.join(lbls)}}};")
  29. cprog.append(inputs)
  30. cprog.append(outputs)
  31. # buffers (empty + weights)
  32. cprog.append("""
  33. int main(int argc, char* argv[]) {
  34. int DEBUG = getenv("DEBUG") != NULL ? atoi(getenv("DEBUG")) : 0;
  35. int X=0, Y=0, chan=0;
  36. stbi_uc *image = (argc > 1) ? stbi_load(argv[1], &X, &Y, &chan, 3) : stbi_load_from_file(stdin, &X, &Y, &chan, 3);
  37. assert(image != NULL);
  38. if (DEBUG) printf("loaded image %dx%d channels %d\\n", X, Y, chan);
  39. assert(chan == 3);
  40. // resize to input[1,3,224,224] and rescale
  41. for (int y = 0; y < 224; y++) {
  42. for (int x = 0; x < 224; x++) {
  43. // get sample position
  44. int tx = (x/224.)*X;
  45. int ty = (y/224.)*Y;
  46. for (int c = 0; c < 3; c++) {
  47. input0[c*224*224 + y*224 + x] = (image[ty*X*chan + tx*chan + c] / 255.0 - 0.45) / 0.225;
  48. }
  49. }
  50. }
  51. net(input0, output0);
  52. float best = -INFINITY;
  53. int best_idx = -1;
  54. for (int i = 0; i < 1000; i++) {
  55. if (output0[i] > best) {
  56. best = output0[i];
  57. best_idx = i;
  58. }
  59. }
  60. if (DEBUG) printf("category : %d (%s) with %f\\n", best_idx, lbls[best_idx], best);
  61. else printf("%s\\n", lbls[best_idx]);
  62. }""")
  63. # CLANG=1 python3 examples/compile_efficientnet.py | clang -O2 -lm -x c - -o recognize && DEBUG=1 time ./recognize docs/showcase/stable_diffusion_by_tinygrad.jpg
  64. # category : 281 (tabby, tabby cat) with 9.452788
  65. print('\n'.join(cprog))