{"id":50467813,"url":"https://github.com/giorgosxou/mlpico","last_synced_at":"2026-06-03T10:00:40.598Z","repository":{"id":360788494,"uuid":"1251712632","full_name":"GiorgosXou/MLPico","owner":"GiorgosXou","description":"Static-allocation MLP inference in ANSI C using 2-slot circular buffer with fixed stride indexing. An easy to use, minimal MLP alternative to GiorgosXou/NeuralNetworks enhanced with PROGMEM, int-quantization etc.","archived":false,"fork":false,"pushed_at":"2026-05-30T12:02:58.000Z","size":66,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-06-01T08:35:22.783Z","etag":null,"topics":["ansi-c","arduino","arduino-library","bare-metal","c","inference","mlp","neural-networks","quantization"],"latest_commit_sha":null,"homepage":"","language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/GiorgosXou.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-05-27T21:02:40.000Z","updated_at":"2026-05-30T20:43:03.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/GiorgosXou/MLPico","commit_stats":null,"previous_names":["giorgosxou/mlpico"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/GiorgosXou/MLPico","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GiorgosXou%2FMLPico","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GiorgosXou%2FMLPico/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GiorgosXou%2FMLPico/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GiorgosXou%2FMLPico/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/GiorgosXou","download_url":"https://codeload.github.com/GiorgosXou/MLPico/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GiorgosXou%2FMLPico/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33814312,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-02T02:00:07.132Z","response_time":109,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ansi-c","arduino","arduino-library","bare-metal","c","inference","mlp","neural-networks","quantization"],"created_at":"2026-06-01T08:30:35.277Z","updated_at":"2026-06-02T09:01:05.711Z","avatar_url":"https://github.com/GiorgosXou.png","language":"C","funding_links":["https://www.paypal.com/donate/?hosted_button_id=3FUJ9ZQSM2VQW"],"categories":[],"sub_categories":[],"readme":"## MLPico - ANSI C (Multi-Layer Perceptron)\n\nA general-purpose header-only statically-allocatable [MLP *(Multi-Layer Perceptron)*](https://en.wikipedia.org/wiki/Multilayer_perceptron) implementation\\\\library written in **ANSI C** that utilizes a 2-slot circular-buffer with fixed stride indexing, for the process of feedforward\\\\prediction\u003cb\u003e;\u003c/b\u003e a technique that provides optimal speed and memory efficiency without compromises across most systems. \n\n\n## Features\n\n1. Supports PROGMEM for AVR MCUs.\n2. Supports int-quantized weights.\n3. Blazingly fast and portable.\n4. Supports Arduino, too.\n5. Memory-efficient.\n6. Simple in use.\n\n\n## Usage\n\nSee examples, [for arduino](https://github.com/GiorgosXou/MLPico/tree/main/examples) or [native-os\\\\bare-metal](https://github.com/GiorgosXou/MLPico/tree/main/native_examples).\n\n\n## Training\nHere's a minimal example showing step-by-step how to train an MLP neural network to emulate a basic digital logic circuit implementing a double XOR gate, defined as ((A⊕B)⊕C):\n\n``` python\n# A generic \"boilerplate\"/\"template\" for training and generating a complete MLPico compatible MLP Neural Network.\n# pip install tensorflow\n\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.layers import Input, Dense\nimport tensorflow as tf\nimport numpy as np\nimport random\n\n\n# Reproducibility\nrandom.seed(23)\nnp.random.seed(41)\ntf.random.set_seed(21)\n\n# =========================================================\n#   Define \u003c-- with what you want, aka. your preferences. \n# =========================================================\n\nUSE_BIASES   = True  # \u003c-- Use biases or not\nUSE_DOUBLE   = False # \u003c-- Use 64 or 32 bit-precision aka. `float` or `double`\nUSE_PROGMEM  = True  # \u003c-- Allow PROGMEM compatibility when used with AVR MCUs\nQUANTIZATION = \"\"    # \u003c-- Use \"int16_t\" or \"int8_t\" if you want quantization\n\nINT8Q  = 0\nINT16Q = 0\nif QUANTIZATION: # 💥 Yes I like to use emojis! it's not ai-slop, deal with it. \n    if not QUANTIZATION in ('int16_t', 'int8_t'): # Why suddenly emojis are bad!? wtf.\n        raise TypeError(\"💥 QUANTIZATION !== `int16_t` or `int8_t`\") # ^^^^^^^^^^^^^^^\n    INT8Q      = 0 if QUANTIZATION == 'int16_t' else 1\n    INT16Q     = int(not INT8Q)\n    INT_LIMIT  = 32768 * INT16Q + 128 * INT8Q\n    INT_RANGE  = 65535 * INT16Q + 255 * INT8Q #     int8_t -128 to 127 mapped to the float range bellow.\n    FP__RANGE  = 200.0 * INT16Q + 51  * INT8Q # \u003c-- 51 = -25.5 to 25.5 float range, feel free to change.\n    INT_LENGTH = len(str(INT_RANGE))\n\n# =========================================================\n\n# Setting up a few stuff about precision and int-quantization.\nDFLOAT = 'float'\nPRECISION = 7\nif USE_DOUBLE:\n    if QUANTIZATION: \n        raise Exception(\"💥 You can't use int-quantization with double-precision\") \n    DFLOAT = 'double'\n    PRECISION = 14\nelse:\n    tf.keras.backend.set_floatx('float32')\nIDFLOAT = QUANTIZATION if QUANTIZATION else DFLOAT\n\n\n# Functions to convert float-to-int \u0026 int-to-float\ndef quantize_float32_to_int(w):\n    S = (FP__RANGE) / (INT_RANGE)\n    return round(w / S) # + Z\n\ndef int_to_float32(q):\n    return np.float32(np.float32(FP__RANGE) / (INT_RANGE)) * np.float32(q)\n\n\n# \u003c-- (Training data) - Define the XOR gate inputs and outputs\ninputs  = np.array([\n    [ 0, 0, 0 ], \n    [ 0, 0, 1 ], \n    [ 0, 1, 0 ], \n    [ 0, 1, 1 ], \n    [ 1, 0, 0 ], \n    [ 1, 0, 1 ], \n    [ 1, 1, 0 ], \n    [ 1, 1, 1 ]\n], dtype = np.float32)\noutputs = np.array([[0], [1], [1], [0], [1], [0], [0], [1]], dtype = np.float32)\n\n# \u003c-- Create a simple MLP neural network\nmodel = tf.keras.Sequential([\n    Input(shape=(3,)), # 3 Inputs/features (no biases) \n    Dense(4, activation='sigmoid', use_bias=USE_BIASES), # Dense  4 units\\neurons\n    Dense(1, activation='sigmoid', use_bias=USE_BIASES)  # Output 1 units\\neurons\n])\n\n# Disaplay a summary of the MLP structure\nmodel.summary()\n\n# Compile the model\noptimizer = Adam(learning_rate=0.091) # \u003c--\nmodel.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy']) # \u003c--\n\n# Train the model\nmodel.fit(inputs, outputs, epochs=300, verbose=1) # \u003c--\n\n# Evaluate the model on the training data\nloss, accuracy = model.evaluate(inputs, outputs)\nprint(f\"Model accuracy: {accuracy * 100:.2f}%\")\n\n# Predict XOR gate outputs\npredictions = model.predict(inputs)\nprint(\"Predictions:\")\nfor i in range(len(inputs)):\n    print(f\"Input: {inputs[i]}, Predicted Output: {predictions[i][0]:.7f}\")\n\n\n# Get input and output layers with the largest amount of neurons\nlayers = [model.input_shape[1]] + [layer.units for layer in model.layers]\nmax_in  = 0 # largest even-indexed layer\nmax_out = 0 # largest  odd-indexed layer\ninout = True\nfor layer in layers:\n    if inout:\n        if layer \u003e max_in: max_in = layer\n    else:\n        if layer \u003e max_out: max_out = layer\n    inout = not inout\n\n\n# Just printing stuff\nprint()\nweights_biases = model.get_weights()\nprint(\"#define NumberOf(arg) ((unsigned int) (sizeof (arg) / sizeof (arg [0])))\")\n\nprint(\n    f\"#define MLPICOPTIMIZE 0B{int(USE_PROGMEM)}{int(USE_DOUBLE)}{INT16Q}{INT8Q}{int(not USE_BIASES)}{int(USE_BIASES)}00\" +\n    \" /* ENABLES \" +\n    (\"(USE_PROGMEM) \"                  if     USE_PROGMEM else \"\") +\n    (\"(USE_64_BIT_DOUBLE) \"            if     USE_DOUBLE  else \"\") +\n    (\"(USE_INT_QUANTIZATION int16_t) \" if     INT16Q      else \"\") +\n    (\"(USE_INT_QUANTIZATION int8_t) \"  if     INT8Q       else \"\") +\n    (\"(MULTIPLE_BIASES_PER_LAYER) \"    if     USE_BIASES  else \"\") +\n    (\"(NO_BIAS) \"                      if not USE_BIASES  else \"\") +\n    \"*/\"\n)\n\n# functions to handle each case\nif not QUANTIZATION:\n    def handle_weight(w, i, j): print(f\"{w[i][j]:{PRECISION+3}.{PRECISION}f}f\", end=\", \")\n    def handle_bias  (b,    j): print(   f\"{b[j]:{PRECISION+3}.{PRECISION}f}f\", end=\", \")\nelse:\n    def handle_weight(w, i, j): \n        x = quantize_float32_to_int(w[i][j])\n        w[i][j] = int_to_float32(x)\n        print(f\"{x:{INT_LENGTH}d}\", end=\", \")\n        if x \u003e= INT_LIMIT or x \u003c -INT_LIMIT:\n            raise RuntimeError(f\"💥 {QUANTIZATION} weight[{i}][{j}]={x} exceeds INT_RANGE={INT_RANGE}. Please adjust FP__RANGE={FP__RANGE} or clip weights to a limit.\") \n\n    def handle_bias(b, j): \n        x = quantize_float32_to_int(b[j])\n        b[j] = int_to_float32(x)\n        print(f\"{x:{INT_LENGTH}d}\", end=\", \")\n        if x \u003e= INT_LIMIT or x \u003c -INT_LIMIT:\n            raise RuntimeError(f\"💥 {QUANTIZATION} bias[{j}]={x} exceeds INT_RANGE={INT_RANGE}. Please adjust FP__RANGE={FP__RANGE} or clip biases to a limit.\") \n\n    hlfpr = FP__RANGE/2\n    print(f\"#define Q_FLOAT_RANGE {FP__RANGE} /* is a float-range of {hlfpr} to -{hlfpr} mapped to int{8 + 8*INT16Q}_t */\")\n\n\nprint(\"#define MLPICO_IMPLEMENTATION /* Defines the implementation inside the header file */\")\n\n\n# check if model has more than one activation function\nacts = {}\nlist_acts = []\nfor layer in model.layers[0:]:\n    l = layer.activation.__name__.replace('_', '')\n    acts[l.upper()] = 1\n    list_acts.append(l)\n\n# define them.\nif len(acts) \u003e 1:\n    print(\"/* Actiavtion functions per layer-to-layer */\")\n    print(\"#define ACTIVATION__PER_LAYER /* allows the use of multiple activation functions to be defined */\")\n    for act in acts:\n        print(f\"    #define {act} /* Defines the core activation function used internally by MLPico */\")\nelif not acts.get(\"SIGMOID\"): # sigmoid is mlpico default \n    print(f\"#define {next(iter(acts))}\")\n\n\nprint(\"#include \u003cmlpico.h\u003e\\n\\n\")\n\nprint(f\"unsigned int layers[] = \" + \"{\" + \",\".join(map(str, layers)) + \"};\")\nprint(f\"{DFLOAT} buffer[{max_in + max_out}];\")\nprint(f\"{DFLOAT} *inputs = buffer;\")\nprint(f\"{DFLOAT} *output;\\n\")\n\nif len(acts) \u003e 1:\n    print(\"const uint8_t activation_functions[] = {\")\n    for act in list_acts:\n        print(f\"  idx_{act}\")\n    print(\"}\\n\")\n\nif USE_BIASES:\n    print(\"/* Pretrained biases */\")\n    print(f\"const {'PROGMEM ' if USE_PROGMEM else ''}{IDFLOAT} biases[] = {{\")\n    for l, (w, b) in enumerate(zip(weights_biases[::2], weights_biases[1::2])):\n        print('  ', end='')\n        for j in range(0, w.shape[1]):\n            handle_bias(b, j)\n        print()\n    print('};\\n')\n\nshift = int(not USE_BIASES) \nprint(\"/* Pretrained weights */\")\nprint(f\"const {'PROGMEM ' if USE_PROGMEM else ''}{IDFLOAT} weights[] = {{\", end=\"\")\nfor l, (w, b) in enumerate(zip(weights_biases[::2-shift], weights_biases[1-shift::2-shift])):\n    print()\n    for j in range(0, w.shape[1]):\n        print('  ', end='')\n        for i in range(0, w.shape[0]):\n            handle_weight(w, i, j)\n        print()\nprint('};\\n')\n\n\nprint(\n    \"MLPico mlp = {\" + \"buffer,\" + (\" biases,\" if USE_BIASES else \"\") + \" weights, layers, \" +\n    f\"{max_in}, NumberOf(layers)}}; /* {max_in} = largest even-indexed layer */ \"\n)\nprint(\"mlpico_print(\u0026mlp);\")\n\n\nif not QUANTIZATION: exit()\n\n# Load quantized weights for NN evaluation\nmodel.set_weights(weights_biases)\n\n# Evaluate the model on the training data again after quantization\nprint()\nloss, accuracy = model.evaluate(inputs, outputs)\nprint(f\"Quantized Model accuracy: {accuracy * 100:.2f}%\")\n\n# Predict XOR gate outputs\npredictions = model.predict(inputs)\nprint(\"Predictions after quantizatioon:\")\nfor i in range(len(inputs)):\n    print(f\"Input: {inputs[i]}, Predicted Output: {predictions[i][0]:.7f}\")\n```\n\n\n## Donate\nMay love shine light to your heart. \n\n- Paypal: https://www.paypal.com/donate/?hosted_button_id=3FUJ9ZQSM2VQW\n- Monero: \u003csub\u003e\u003csup\u003e`89pdRfcusZr39HNFXEToN38ArKtm7y4o6aHhRfdtW75hMuv3h3QT2TPWZ5F2kBAqRPTxFfCQBtbKSMErcG6PMzeu31XU4aL`\u003c/sup\u003e\u003c/sub\u003e\n\n\n## Outro\nIf you need something more feature-complete and [powerful](https://github.com/GiorgosXou/ATTiny85-MNIST-RNN-EEPROM); I then recommend you to take a *(non-judgmental)* look into my [NeuralNetworks library](https://github.com/GiorgosXou/NeuralNetworks) *(that I based MLPico on)*.\n\n\n\u003ci\u003e\u003csub\u003e (This library is not vibe coded. [Here's the proof](https://github.com/GiorgosXou/NeuralNetworks/commit/4d1f3205afb7f5cbc5378e6043344151c52c9cea) that I'm developing MLP algorithms since 2019; way before the AI-slop epidemic. and [here](https://github.com/GiorgosXou/NeuralNetworks#-research)'s the whole research behind it) \u003c/sub\u003e\u003c/i\u003e\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgiorgosxou%2Fmlpico","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgiorgosxou%2Fmlpico","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgiorgosxou%2Fmlpico/lists"}