希望快啲有國產平價算力卡出現,普及化ai,等一般消費者都可以享受到。
caihk 發表於 23-2-2025 08:38


還希望減低運作AI時的能源消耗,好使電池驅動的設備也可以使用AI。

TOP

本帖最後由 hkguy2020 於 2025-2-23 16:00 編輯

我仲諗緊點樣 code:  RKLLM-Gradio, local pre-trained NPU enabled LLM and LangChain.

問過自己幾個 local llm, Llama-3.1-Instruct-8B 幾全面, 畀大家參考吓. 當然有 code 係好, 但真係 run 得到, 先至嚟料.

RKLLM Model, Llama-3.1-Instruct-8B has been initialized successfully!
==============================
I'll guide you through the process of setting up Rockchip RK3588 with RKLLM (Rockchip Large Language Model) using Gradio for local LLM inference, leveraging the Neural Processing Unit (NPU) for acceleration and integrating LangChain for programming.

**Prerequisites:**

1. **RK3588 board**: You'll need a Rockchip RK3588-based single-board computer.
2. **Ubuntu 20.04 or later**: Install Ubuntu on your RK3588 board.
3. **Python 3.x**: Ensure Python is installed on your system.
4. **LangChain and Gradio**: Install the required libraries using pip:
   ```bash
pip install langchain gradio transformers torch
```
5. **RKLLM model**: You can use a pre-trained LLM like T5 or BART, which are compatible with RK3588's NPU.

**Step 1: Prepare your environment**

Create a new directory for your project and navigate to it:
```bash
mkdir rk3588-lm-project
cd rk3588-lm-project
```
**Step 2: Install the required dependencies**

Update your package list and install the necessary packages:
```bash
sudo apt update && sudo apt upgrade -y

# Install OpenCL for NPU acceleration
sudo apt-get install ocl-icd-opencl-dev libopencl1

# Install CUDA (for GPU support, but not required for this example)
sudo apt-get install nvidia-cuda-toolkit
```
**Step 3: Clone the RKLLM repository**

Clone the RKLLM GitHub repository to access pre-trained models and utilities:
```bash
git clone https://github.com/Rockchip-LiMe/rkllm.git
cd rkllm
```
**Step 4: Prepare your LLM model**

You can use a pre-trained model from the `rkllm` repository or download one of your choice. For this example, we'll use the pre-trained T5-Base model:
```bash
# Download the pre-trained T5-Base model
wget https://github.com/Rockchip-LiMe ... v0.1/t5-base.tar.gz

# Extract the model files
tar -xvf t5-base.tar.gz
```
**Step 5: Install LangChain and Gradio**

Install the required libraries using pip:
```bash
pip install langchain gradio transformers torch
```
**Step 6: Create a sample project with LangChain and Gradio**

Create a new Python file (`app.py`) to define your LLM-based application:
```python
import gradio as gr
from langchain.agents import ChainAgent
from transformers import T5Tokenizer

# Load the pre-trained model and tokenizer
tokenizer = T5Tokenizer.from_pretrained('t5-base')
model = torch.load('./models/t5-base.pth', map_location='cuda')

# Define a sample function using LangChain's ChainAgent
def chat(input_text):
    agent = ChainAgent(
        model=model,
        tokenizer=tokenizer,
        max_length=1024,
        min_length=64,
    )
   
    response = agent.generate_response(input_text)
    return response

# Create a Gradio interface for local LLM inference
demo = gr.Interface(chat, inputs=[gr.Textbox(label="Input")], outputs=[gr.Textbox(label="Output")])

# Launch the demo
demo.launch()
```
**Step 7: Run your application**

Run your Python script using:
```bash
python app.py
```
This will launch a Gradio interface for local LLM inference, allowing you to interact with your pre-trained model.

Note that this is just a basic example to get you started. You can customize the LangChain and Gradio components to suit your specific requirements and integrate them with other AI models or libraries as needed.


--------------------------------------------------------------------------------------
Stage         Total Time (ms)  Tokens    Time per Token (ms)      Tokens per Second      
--------------------------------------------------------------------------------------
Prefill       2118.11          94        22.53                    44.38                  
Generate      281084.43        798       353.18                   2.83                    
--------------------------------------------------------------------------------------

詳細睇 code, 唔 work. 最重要嘅 LangChain wrap RKLLM, 竟然無. ChatGPT 咁樣寫:

📌 3. Create a LangChain Wrapper for RKLLM
RKLLM runs in the terminal, so we create a custom LangChain LLM class to call it.

Create rkllm_langchain.py:
from langchain.llms.base import LLM
import subprocess

class RKLLM(LLM):
    model_path: str

    def _call(self, prompt: str, stop=None, run_manager=None):
        # Run RKLLM inference
        result = subprocess.run(["./rkllm_infer", self.model_path, prompt], capture_output=True, text=True)
        return result.stdout.strip()

    @property
    def _identifying_params(self):
        return {"model_path": self.model_path}

Test it:
from rkllm_langchain import RKLLM

rk_llm = RKLLM(model_path="llama-7b.rknn")
response = rk_llm("Tell me a joke.")
print(response)

Programming 其實係自家嘢 (當然最奇怪係 LangChain 點樣 wrap 到 RKLLM), 呢個位寫到咁多, 唔再寫囉.

TOP

... 不過睇啲rk3588教學,rockchip用起上黎都幾麻煩, 要將native模型 -----〉轉成onnx格式 ----〉rknn 格式, ...
caihk 發表於 2025-2-23 08:38


rk3588 格式嘅 llm, 可以直接 download, 已經轉換好格式:

Screenshot 2025-02-23 100730.jpg

huggingface

TOP

本帖最後由 hkguy2020 於 2025-2-24 16:59 編輯

尋日, 開始學 RAG, 試最簡單嘅 RAG pipeline (program 未睇得明, 所以要試, 試過就明), 但要 openai api key account, 我23年已開:

# OpenAI Setup
os.environ['OPENAI_API_KEY'] = ''
openai.api_key = os.environ['OPENAI_API_KEY']

# Load Documents
loader = WebBaseLoader(
    web_paths=("https://kbourne.github.io/chapter1.html",),
    bs_kwargs=dict(
        parse_only=bs4.SoupStrainer(
            class_=("post-content", "post-title", "post-header")
        )
    ),
)
docs = loader.load()

用 Python 嚟行, 出 error,  insufficient quota .... 我嘅 openai api key account trial period 已經 expired. 想畀 US$5.0 買都唔得, 搵唔到原因 (唔喺香港, 唔係用 HK$ credit card), 再諗諗, 用 local llm 應該可以呀! 下一步改 code 行自己 local llm, 唔駛畀錢

如果買到 credit,  已經駛咗冤枉錢.

TOP

rk3588 -- 文字生成圖片, 用 Stable Diffusion, 只係用 rk3588 上的 NPU, 無需要加 AI board:



NPU accelerated SD1.5 LCM on $130 RK3588 SBC, 30 seconds per image!

TOP

本帖最後由 hkguy2020 於 2025-2-27 09:12 編輯

我自己都試了上面個 steps, Stable Diffusion 文字生成圖片, 幾好玩, 時間要大概一分鐘先製到圖 (Orange Pi Max, DDR5 16gb, NPU).

之後諗文字生成圖片點樣用喺 ecommerce app?

個 app 可以寫成 user search 完 product 後, 如果唔啱心水, 可以 input 自己想要 product 嘅特徵(用 parameters 形式), Stable Diffusion 生成 user 想要 product 嘅圖片, 同時搵埋 market 上已有嘅相似 product 畀 user(可以做多啲生意). 我會試吓寫 (當然, app 要 call 自己 Stable Diffusion server, server 行 local llm).

依家要成分鐘先製到圖, 現實只可以等10秒之內, 現有嘅 opi 5 max 無可能, 如果一齊用 opi 5 max NPU + raspi 5 Hailo 10H 有機會嗎?

TOP

要 explore 嘅 features 已經全部試過: (1) rkllm server via Gradio, 可以用 web base access (rkllm default 係用 NPU), (2) 試咗 Langchain 喺 rockchip 上嘅 development 同一般嘅 application 係乜 (Langchain 依家已然係主流), (3) Langchain 無 rkllm 嘅 standard library, 唔似 Ollama, 有 Langchain OllamaLLM, 要自己寫 wrapper, ok 嘅. 問過 ChatGpt, 因為 RK3588 唔流行喎, (4) Stable Diffusion running on RK3588, 用到 NPU, (5) moble app 點去 inference local llm, 可以參考呢個: LLAMA.CPP DART

另外, 確認咗 rkllm-toolkit (= rkllm sdk) 唔可以喺 Soc 做 development (即係無得 from rkllm.api import RKLLM), 要用 rockchop x86 based pc 先得, 但 Soc 可以用 C/C++ programming interfaces access local llm (librkllmrt.so). w8a8 format 嘅 llm 可以係 Huggingface download.

整個過程, 可以用刺激好玩嚟形容, 困難當然極多, 但 programming 就係 problem solving. 可以喺咁僻嘅 rockchip Soc 做 AI development 係好有成就感同慳錢, 有 NPU, local llm 嘅 performance 唔錯. 如果自己覺得 development 經驗夠, 少少錢敢去搏嘅, 成功機會都好大.

Hailo-10H 到有得賣時, 如果唔貴同好玩嘅, 都可能會買嚟玩下. 現有嘅 Orange Pi 5 Max 16gb, Ras Pi 5 16gb 同 8gb, 睇吓成唔成功做到 Python AI project development + CMS backend server + Flutter mobile app development, 賣得幾張單都好. 如果得, 收番啲成本.

TOP