Knowledge Base · Learning paths
Fast and Slow Thinking with LLMs: Adapting Your LLM Use Cases II - Running Flux on Mac, Edge Devices, and WeChat
This guide explains how to deploy the FLUX.1 [schnell] model on a Mac Mini M1 and Raspberry Pi 5 using WasmEdge (LlamaEdge) for local text-to-image generation on edge devices. It also shows how to build a prompt-based drawing bot on WeChat with Dify and CoW, offering a practical no-NVIDIA-GPU solution.
Translated from Chinese by AI. Spotted an issue? Use the feedback button.
Author: ZimaBlueAI Qimalan
Introduction
A practical example of running LlamaEdge (WasmEdge) with FLUX.1 on edge devices. FLUX.1 is an advanced text-to-image generation model from Black Forest Labs, available in three variants: FLUX.1 [pro], FLUX.1 [dev], and FLUX.1 [schnell]. These variants cater to different user needs, with open-source options and enterprise customization.
This article details how to deploy FLUX.1 [schnell] on a Mac Mini M1 and Raspberry Pi 5B, using the WasmEdge framework for efficient text-to-image generation. The steps cover downloading model files, installing the WasmEdge plugin, and starting the API server. It also explores an example of image generation on WeChat using Dify and the CoW project, providing a practical case study of LlamaEdge in edge computing.
Keywords: FLUX.1, M1, Raspberry Pi 5B, Edge, LlamaEdge, Dify, CoW
Zima | Author
Continuing our exploration of practical applications of LlamaEdge (WasmEdge)
ZimaBlueAI, WeChat Official Account: Qimalan LLMs, Thinking Fast and Slow: Tailoring LLMs to Your Use Cases—Deploying Large Language Models on Raspberry Pi and Smartphones
FLUX.1
FLUX.1 is an advanced suite of text-to-image generation models from Black Forest Labs. It includes three variants—FLUX.1 [pro], FLUX.1 [dev], and FLUX.1 [schnell]—to meet different user needs.
FLUX.1 [pro] is a closed-source model offering the highest-quality image generation, with advanced prompt adherence, visual quality, image detail, and output diversity. Access can be requested through the official API, and enterprise customization is supported.
FLUX.1 [dev] is an open-source model for non-commercial use, distilled directly from FLUX.1 [pro]. It delivers similar image quality and prompt adherence with greater efficiency. It is available on Hugging Face and can be tried on platforms such as Replicate or fal.ai.
FLUX.1 [schnell] is an open-source model that permits commercial use. Tailored specifically for local development and personal use, it offers the fastest generation speed and the smallest memory footprint. It is publicly available under the Apache 2.0 license, making it suitable for rapid prototyping and personal projects.
FLUX.1 has 12 billion parameters, far surpassing SD3 Medium's 2 billion. It outperforms popular models such as Midjourney v6.0, DALL·E 3 (HD), and SD3-Ultra in image quality, prompt adherence, adaptability to different image dimensions, typography, and output diversity, setting a new state of the art in image synthesis.
FLUX.1 AI uses a hybrid architecture combining transformer and diffusion technologies to generate accurate images from text prompts. It employs cutting-edge techniques such as flow matching and optimization to produce high-quality images.
Key features of FLUX.1 AI include cutting-edge performance, text handling, complex composition, and improved rendering of human hands. It can be used on platforms such as Replicate, fal.ai, and ComfyUI, with clearly defined pricing details and usage limits.
In addition, FLUX.1 AI allows users to fine-tune it on their own datasets to generate images in specific styles or on particular themes.
In this article, we first try running FLUX.1 [schnell] on a Mac Mini M1 without an NVIDIA GPU or complex workflow-building tools such as ComfyUI. Next, we explore whether it can run on a Raspberry Pi 5B edge device. Finally, we use Dify and the CoW project to build a WeChat application that generates images from prompts sent through WeChat.
Running FLUX.1 on a Mac Mini M1
32 GB of RAM or more is recommended
0x01 Install WasmEdge and the SD (Stable Diffusion) Plugin
You need to install WasmEdge >= 0.14.1 and the latest SD plugin.
curl -sSf https://raw.githubusercontent.com/WasmEdge/WasmEdge/master/utils/install_v2.sh | bash -s -- -v 0.14.1
Installation on an Apple Silicon M1 Mac
# Download the Stable Diffusion plugin for Macs with Apple Silicon: curl -LO https://github.com/WasmEdge/WasmEdge/releases/download/0.14.1/WasmEdge-plugin-wasmedge_stablediffusion-metal-0.14.1-darwin_arm64.tar.gz
# Extract the plugin to $HOME/.wasmedge/plugin (automatically created after installing wasmedge): tar -xzf WasmEdge-plugin-wasmedge_stablediffusion-metal-0.14.1-darwin_arm64.tar.gz -C $HOME/.wasmedge/plugin
0x02 Download the FLUX.1[schnell] Model Files
We recommend using hfd.sh or downloading directly with aria2.
ZimaBlueAI, WeChat Official Account: Qima Blue Thinking Fast and Slow with LLMs: Tailoring LLMs to Your Use Cases—Running Large Language Models on Raspberry Pi and Mobile Phones
Here, we use hfd.sh.
hfd.sh second-state/FLUX.1-schnell-GGUF --tool aria2c -x 4
If you don't want to download all the model files, you can use aria2 or curl to download individual files.
# Main modelaria2c -x 4 -s 4 -k 1M -c "https://hf-mirror.com/second-state/FLUX.1-schnell-GGUF/resolve/main/flux1-schnell-Q4_0.gguf" -d "." -o "flux1-schnell-Q4_0.gguf"
# VAE filearia2c -x 4 -s 4 -k 1M -c "https://hf-mirror.com/second-state/FLUX.1-schnell-GGUF/resolve/main/ae-f16.gguf" -d "." -o "ae-f16.gguf"
# clip_l encoderaria2c -x 4 -s 4 -k 1M -c "https://hf-mirror.com/second-state/FLUX.1-schnell-GGUF/resolve/main/clip_l-Q8_0.gguf" -d "." -o "clip_l-Q8_0.gguf"
# t5xxl encoderaria2c -x 4 -s 4 -k 1M -c "https://hf-mirror.com/second-state/FLUX.1-schnell-GGUF/resolve/main/t5xxl-Q4_K.gguf" -d "." -o "t5xxl-Q4_K.gguf"
0x03 Download the API Server Application
The API server is a cross-platform Wasm application that can run on different CPU and GPU devices.
curl -LO https://github.com/LlamaEdge/sd-api-server/releases/latest/download/sd-api-server.wasm
0x04 Start the API Server
Run the following command in the directory containing the models and sd-api-server.wasm:
FLUX.1-schnell-GGUF
├── ae-f16.gguf
├── clip_l-Q8_0.gguf
├── flux1-schnell-Q4_0.gguf
├── sd-api-server.wasm
└── t5xxl-Q4_K.gguf
wasmedge --dir .:. sd-api-server.wasm \ --model-name flux1-schnell \ --diffusion-model flux1-schnell-Q4_0.gguf \ --vae ae-f16.gguf \ --clip-l clip_l-Q8_0.gguf \ --t5xxl t5xxl-Q4_K.gguf
After loading completes successfully, you will see:
Listening on 0.0.0.0:8080
This indicates that the server has started successfully.
0x05 Text-to-Image
curl -X POST 'http://localhost:8080/v1/images/generations' \ --header 'Content-Type: application/json' \ --data '{ "model": "flux1-schnell", "prompt": "Astronaut, wearing futuristic astonaut outfit with space helmet, beautiful body and face, very breathtaking beautiful image, cinematic, 4k, epic Steven Spielberg movie still, sharp focus, emitting diodes, smoke, artillery, sparks, racks, system unit, motherboard, by pascal blanche rutkowski repin artstation hyperrealism painting concept art of detailed character design matte painting, 4 k resolution blade runner", "cfg_scale": 1.0, "sample_method": "euler", "steps": 4 }'
If everything is configured correctly, after a few minutes the terminal will display the following output and save the generated image as “output.png”:
{"created":1728015570,"data":[{"url":"/archives/file_68f82479-f0db-44ed-adfc-ef2463796fcb/output.png","prompt":"Astronaut, wearing futuristic astonaut outfit with space helmet, beautiful body and face, very breathtaking beautiful image, cinematic, 4k, epic Steven Spielberg movie still, sharp focus, emitting diodes, smoke, artillery, sparks, racks, system unit, motherboard, by pascal blanche rutkowski repin artstation hyperrealism painting concept art of detailed character design matte painting, 4 k resolution blade runner"}]}
Running FLUX.1 on Raspberry Pi 5B
To run it on a Raspberry Pi, we need to replace the Stable Diffusion plugin downloaded in step 0x01 above:
# Download the Stable Diffusion plugin for Raspberry PI5B aarch64: curl -LO https://github.com/WasmEdge/WasmEdge/releases/download/0.14.1/WasmEdge-plugin-wasmedge_stablediffusion-0.14.1-manylinux_2_28_aarch64.tar.gz
# Extract the plugin to $HOME/.wasmedge/plugin (automatically created after installing wasmedge) tar -xzf WasmEdge-plugin-wasmedge_stablediffusion-0.14.1-manylinux_2_28_aarch64.tar.gz -C $HOME/.wasmedge/plugin
Then, when running step 0x04, try to choose a model with lower-bit quantization (or download the safetensors file yourself and requantize it using llama.cpp):
wasmedge --dir .:. sd-api-server.wasm \ --model-name flux1-schnell \ --diffusion-model flux1-schnell-Q4_0.gguf \ --vae ae-f16.gguf \ --clip-l clip_l-Q8_0.gguf \ --t5xxl t5xxl-Q2_K.gguf
A memory error occurred. Wait for the next version, or quantize to Q2 and try again.
Segmentation fault
Alternatively, download:
aria2c -x 4 -s 4 -k 1M -c "https://huggingface.co/lllyasviel/FLUX.1-schnell-gguf/resolve/08fc03e0dc5c1466c60fb7e108974ded1124c515/flux1-schnell-Q2_K.gguf" -d "." -o "flux1-schnell-Q2_K.gguf"
For a precise estimate of VRAM and RAM requirements, refer to this formula:
| Field | Explanation |
|---|---|
| M | GPU memory (in gigabytes) |
| P | Number of parameters in the model. For example, a 7B model has 7 billion parameters. |
| 4B | 4 bytes, representing the number of bytes used per parameter |
| 32 | 32 bits per byte |
| Q | Bit width used when loading the model: 4, 8, or 16 bits |
| 1.2 | Accounts for additional overhead during memory loading |
Testing again
wasmedge --dir .:. sd-api-server.wasm \ --model-name flux1-schnell \ --diffusion-model flux1-schnell-Q2_K.gguf \ --vae ae-f16.gguf \ --clip-l clip_l-Q8_0.gguf \ --t5xxl t5xxl-Q2_K.gguf
It worked!!!
But memory is still insufficient, and errors are extremely likely. Try this prompt:
A dramatic landscape on an exoplanet with a breathtaking view of a ringed gas giant in the sky. The planet surface is rugged and alien, with strange rock formations and vibrant, otherworldly vegetation. The rings of the gas giant cast colorful shadows and reflections, creating a surreal and captivating environment.
Using FLUX.1 in WeChat with Dify+CoW
The following example uses this environment:
CPU: Intel 13th Gen 13900KF
RAM: 64GB
GPU: nVidia RTX 4900 24GB
OS: win11 pro+WSL2+Ubuntu 20.04
Dify
Dify.AI is an open-source platform for developing large language model (LLM) applications. It allows users to orchestrate LLM applications ranging from AI agents to complex AI workflows, and includes a RAG (Retrieval-Augmented Generation) engine. Dify.AI aims to provide industry-specific chatbots and AI assistants that can incorporate domain knowledge to facilitate human–AI collaboration.
Here are some of Dify.AI's key features and benefits:
-
Rapid Deployment: Users can deploy a customized chatbot or AI assistant in just 5 minutes.
-
Creative Document Generation: Dify.AI can generate clear, logically structured documents from a knowledge base, with no length limit.
-
Long-document summarization : It can easily summarize long documents.
-
Custom APIs : Dify.AI provides custom APIs to securely connect business knowledge and unlock deeper insights from LLMs.
-
Connect to LLMs worldwide : It can connect to large language models (LLMs) from around the world.
-
Production-ready : Dify.AI is closer to production readiness than LangChain.
-
Open source : Dify.AI is an open-source project, allowing the community to use and improve it widely.
Developers and users can find resources such as the project's source code, documentation, installation guides, usage instructions, and contribution guidelines in Dify.AI's GitHub repository at https://github.com/langgenius/dify.gi t and at https://docs.dify.ai/.
CoW
c hatgpt-on-wechat (CoW for short) is an intelligent conversational bot project based on large language models, designed to offer multi-platform deployment and a rich feature set. Here are some of the CoW project's key features and advantages:
-
Multi-platform deployment : CoW supports deployment on multiple platforms, including WeChat Official Accounts, WeCom apps, Feishu, and DingTalk.
-
Basic conversation : CoW can intelligently respond to private and group chat messages, retain context across multiple turns, and support various language models, such as GPT-3.5, GPT-4, GPT-4o, Claude, Gemini, ERNIE Bot, iFlytek Spark, Qwen, ChatGLM-4, and Kimi (Moonshot AI).
-
Speech recognition : CoW can recognize voice messages and reply with text or voice. It supports various speech models and services, such as Azure, Baidu, Google, and OpenAI (Whisper/TTS).
-
Image generation : CoW supports image generation, image recognition, and image-to-image tasks (such as photo restoration), with options including DALL-E 3, Stable Diffusion, Replicate, Midjourney, CogView-3, and vision models.
-
Extensive plugins : CoW supports custom plugin extensions, with existing plugins for switching between personas, text adventures, sensitive-word filtering, chat history summarization, document summarization and chat, web search, and more.
-
Tools : CoW can interact with the operating system and the internet, supporting features such as searching for up-to-date information, mathematical calculations, weather and news queries, and webpage summarization.
-
Knowledge base : CoW allows users to upload knowledge base files to customize their own bots, which can serve as digital twins, intelligent customer service bots, or assistants for private customer communities.
-
Open source : The CoW project is open source on GitHub and Gitee, meaning developers and users can freely access, use, modify, and distribute the code.
Project links:
I won't go into too much detail about Dify for now. Like AutoGPT, MetaGPT, FastGPT, and others, it is an LLM application development platform that lets you build your own AI agents and workflows. AM is built on Dify. Here is a preview of its node-based workflow:
Back to LlamaEdge: we can build our own API extension to call the FLUX.1 API Server mentioned above (a bit like nesting dolls).
For instructions on API extensions, see: https://docs.dify.ai/zh-hans/guides/extension/api-based-extension, though this approach appears to no longer be used in version 0.8.3 (Dify has quite a few issues with feature updates or version conflicts, so you may need to make your own changes or submit a PR).
You can also integrate the dify-on-wechat project, create a dify_image.py program under bot/dify/, and add the image-generation call logic to the Dify bot. For example, you can trigger the call with a query that starts with “draw” followed by a prompt. I will add dify_image.py to my code repository later.
def create_img(self, query, retry_count=0): query_en = translate_text(query)
# Define request parameters text_to_image_url = conf().get("dify_text_to_image_url", self.dify_api_image_base + "/images/generations")
headers = { 'Content-Type': 'application/json' } data = { "model": "flux1-schnell", "prompt": query_en, "cfg_scale": 1.0, "sample_method": "euler", "steps": 4 }
try: # Send a POST request response = requests.post(text_to_image_url, headers=headers, json=data) # Parse the JSON response parsed_json = response.json()
# Get the URL url = parsed_json["data"][0]["url"] # Print the response status code and content print("URL:", url) return True, "http://host.docker.internal:5000/" + url ## Set up an image server to forward local image URLs
except Exception as e: logger.warn(e) if retry_count < 3: time.sleep(15) logger.warn("[DIFY] ImgCreate RateLimit exceed, retry attempt {}".format(retry_count + 1)) return self.create_img(query, retry_count + 1) else: return False, "Something went wrong while generating the image. Please wait a bit and try again." except Exception as e: logger.exception(e) return False, "Something went wrong while generating the image. Please wait a bit and try again."
The image server is very simple: just write a Flask app and an HTML file:
app.py
import osfrom flask import Flask, render_template, send_from_directory, requestfrom PIL import Imagefrom io import BytesIO
app = Flask(__name__)
# Image storage path IMAGE_FOLDER = 'local image storage path'
def walk_images(folder): images = [] folders = [] for root, dirs, files in os.walk(folder): for file in files: if file.lower().endswith(('.png', '.jpg', '.jpeg')): img_path = os.path.join(root, file) img = Image.open(img_path) thumb = img.copy() thumb.thumbnail((100, 100)) output = BytesIO() thumb.save(output, format='JPEG') images.append({ 'type': 'image', 'path': os.path.relpath(img_path, IMAGE_FOLDER), 'thumb': output.getvalue() }) for dir_name in dirs: folders.append(os.path.join(root, dir_name)) return images, folders
@app.route('/')def index(): images, folders = walk_images(IMAGE_FOLDER) return render_template('index.html', images=images, folders=folders)
@app.route('/<path:path>')def get_file(path): return send_from_directory(IMAGE_FOLDER, path)
@app.route('/thumbs/<path:path>')def get_thumb(path): img_path = os.path.join(IMAGE_FOLDER, path) img = Image.open(img_path) output = BytesIO() img.thumbnail((300, 300)) img.save(output, format='JPEG') return output.getvalue()
if __name__ == '__main__': app.run(debug=True, host="host.docker.internal", port=5000)
template/index.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Image Gallery</title> <style> .thumbnail { width: 100px; height: 100px; object-fit: cover; } .gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px; } .folder-icon { background-color: #f0f0f0; padding: 10px; border-radius: 5px; text-align: center; cursor: pointer; } .folder-icon:hover { background-color: #e0e0e0; }</style></head><body> <h1>Image Gallery</h1> <div class="gallery"> {% for item in files %} {% if item.type == 'folder' %} <div class="folder-icon" onclick="location.href='/{{ item.name }}';">{{ item.name }}</div> {% else %} <img src="{{ url_for('get_thumb', path=item.name) }}" alt="{{ item.name }}"> {% endif %} {% endfor %} </div></body></html>
All the code above can be handled by Phind, Copilot, Cursor, or Zed + ollama + a coding-focused large language model (LLM). Still, the architecture feels overcomplicated and not elegant enough. Once I’ve cleaned it up, I’ll package it as a complete solution and publish a repo.
Here are some screenshots:
Next time, I’ll try a WASM API server for image-to-image, Whisper, and RAG.
About
Qimalan Intelligence
Focusing on Technology, Life, and Truth