colab-hf-chat 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # colab-hf-chat
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 在 Google Colab GPU 上运行 Hugging Face 聊天模型,通过 SSH 转发在本机使用 vLLM 的 OpenAI 兼容 API。CLI 可自动安装 Google Colab CLI、引导 Google 授权,并显示账户剩余 Compute Units(CU)。
4
+
5
+ ## 安装和启动
6
+
7
+ 需要 Node.js 18+。macOS 和 Linux 使用本机 Bash、curl 和 OpenSSH。Windows 使用已初始化的 WSL 2 Linux 发行版,并需要 WSL 的 localhost 转发。
8
+
9
+ ```bash
10
+ npm install -g colab-hf-chat --registry=https://registry.npmjs.org/
11
+ colab-hf-chat
12
+ ```
13
+
14
+ 1. 首次使用时,按提示用自己的 Google 账号授权 Colab CLI。
15
+ 2. 输入公开的 Hugging Face 聊天模型 ID。默认使用 `Qwen/Qwen2.5-0.5B-Instruct`、L4 GPU 和本地端口 `8000`。
16
+ 3. 看到 **API 已就绪** 后,将 OpenAI 兼容客户端的 Base URL 设为 `http://127.0.0.1:8000/v1`,模型填你输入的模型 ID。若客户端要求 API Key,可填 `local`。
17
+ 4. 使用结束后按 **Ctrl+C** 释放 GPU 会话。
18
+
19
+ 首次启动会安装 vLLM 并下载模型权重。模型需受 vLLM 支持,并能放入所选 GPU 的显存。GPU 可用性由 Colab 决定。API 监听本机回环地址。
20
+
21
+ ## 调用示例
22
+
23
+ ```bash
24
+ curl -fsS http://127.0.0.1:8000/v1/models
25
+ curl -fsS http://127.0.0.1:8000/v1/chat/completions \
26
+ -H 'Content-Type: application/json' \
27
+ -d '{"model":"Qwen/Qwen2.5-0.5B-Instruct","messages":[{"role":"user","content":"你好"}],"max_tokens":64}'
28
+ ```
29
+
30
+ ## 只查 Colab 额度
31
+
32
+ ```bash
33
+ colab-hf-chat usage
34
+ ```
35
+
36
+ 显示剩余 CU、当前每小时消耗和活跃会话数。此命令不申请 GPU。
37
+
38
+ 本项目是独立 CLI,使用 [Google Colab CLI](https://github.com/googlecolab/google-colab-cli) 和 [vLLM](https://docs.vllm.ai/)。
package/cli.cjs ADDED
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const { spawn, spawnSync } = require('node:child_process');
5
+ const { join } = require('node:path');
6
+
7
+ const args = process.argv.slice(2);
8
+ if (args.includes('--help') || args.includes('-h')) {
9
+ console.log('colab-hf-chat [usage]\n\n交互启动 Colab GPU 模型,或用 usage 查询剩余 CU。');
10
+ process.exit(0);
11
+ }
12
+ if (args.length > 1 || (args.length === 1 && args[0] !== 'usage')) {
13
+ console.error('用法: colab-hf-chat [usage]');
14
+ process.exit(2);
15
+ }
16
+
17
+ const windows = process.platform === 'win32';
18
+ if (!windows && !['linux', 'darwin'].includes(process.platform)) {
19
+ console.error('支持 Linux、macOS,以及安装了 WSL 的 Windows。');
20
+ process.exit(1);
21
+ }
22
+ let script = join(__dirname, 'wizard.sh');
23
+ if (windows) {
24
+ const result = spawnSync('wsl.exe', ['--exec', 'wslpath', '-a', script], {
25
+ encoding: 'utf8',
26
+ windowsHide: true,
27
+ });
28
+ if (result.error || result.status !== 0 || !result.stdout.trim().startsWith('/')) {
29
+ console.error('请先运行 wsl --install,并打开 Linux 发行版完成初始化。');
30
+ if (result.stderr) console.error(result.stderr.trim());
31
+ process.exit(1);
32
+ }
33
+ script = result.stdout.trim();
34
+ }
35
+ const child = windows
36
+ ? spawn('wsl.exe', ['--exec', 'bash', script, ...args], { stdio: 'inherit' })
37
+ : spawn('bash', [script, ...args], { stdio: 'inherit' });
38
+
39
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
40
+ process.once(signal, () => {
41
+ if (!windows) child.kill(signal);
42
+ });
43
+ }
44
+ child.once('error', (error) => {
45
+ console.error(error.message);
46
+ process.exitCode = 1;
47
+ });
48
+ child.once('exit', (code, signal) => {
49
+ const signalExit = { SIGINT: 130, SIGTERM: 143, SIGHUP: 129 };
50
+ process.exitCode = code ?? signalExit[signal] ?? 1;
51
+ });
package/deploy.sh ADDED
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
4
+ COLAB="${COLAB_BIN:-colab}"
5
+ verify_space() {
6
+ local repo="$1" base_url health prediction
7
+ hf spaces wait "$repo" --timeout 10m >&2
8
+ base_url="$(hf spaces info "$repo" --json | python3 -c '
9
+ import json
10
+ import re
11
+ import sys
12
+
13
+ info = json.load(sys.stdin)
14
+ host = info.get("host") or ""
15
+ if info.get("private") is not False or not re.fullmatch(r"https://[a-z0-9-]+[.]hf[.]space/?", host):
16
+ sys.exit("Space metadata does not contain a public hf.space URL")
17
+ print(host.rstrip("/"))
18
+ ')"
19
+ health="$(curl -fsS --retry 4 --max-time 20 "$base_url/health")"
20
+ prediction="$(curl -fsS --max-time 30 "$base_url/predict" \
21
+ -H 'Content-Type: application/json' \
22
+ -d '{"text":"I really loved this movie."}')"
23
+ python3 - "$health" "$prediction" <<'PYVERIFY'
24
+ import json
25
+ import sys
26
+
27
+ health, prediction = map(json.loads, sys.argv[1:])
28
+ if (
29
+ health.get("status") != "ready"
30
+ or not health.get("model")
31
+ or health["model"] != prediction.get("model")
32
+ or not prediction.get("label")
33
+ or not isinstance(prediction.get("score"), (float, int))
34
+ or not 0 <= prediction["score"] <= 1
35
+ ):
36
+ sys.exit("Unexpected response from the public model API")
37
+ print(json.dumps(prediction))
38
+ PYVERIFY
39
+ printf '公网 API %s/predict\n在线试用 %s/docs\n' "$base_url" "$base_url"
40
+ }
41
+
42
+ case "${1:-}" in
43
+ usage)
44
+ exec "$COLAB" usage
45
+ ;;
46
+ colab)
47
+ session="${2:-hf-model-check-$(date +%s)-$$}"
48
+ "$COLAB" new -s "$session"
49
+ trap '"$COLAB" stop -s "$session" || echo "请手动停止 Colab 会话 $session" >&2' EXIT
50
+ trap 'exit 130' INT
51
+ trap 'exit 143' TERM
52
+ "$COLAB" install -s "$session" -r "$ROOT/space/requirements.txt"
53
+ "$COLAB" upload -s "$session" "$ROOT/space/model.py" /content/hf_deploy_model.py
54
+ model_env=()
55
+ for name in MODEL_ID MODEL_REVISION MODEL_FILE; do
56
+ if [[ -n "${!name:-}" ]]; then
57
+ model_env+=(--env "$name=${!name}")
58
+ fi
59
+ done
60
+ "$COLAB" exec -s "$session" --timeout 300 ${model_env[@]+"${model_env[@]}"} <<'PY'
61
+ import json
62
+ import sys
63
+ sys.path.insert(0, "/content")
64
+ from hf_deploy_model import Classifier
65
+ model = Classifier()
66
+ print(json.dumps(model.predict("I really loved this movie.")))
67
+ PY
68
+ ;;
69
+ publish)
70
+ repo="${2:?请提供 Hugging Face 目标 Space,格式为 owner/space-name}"
71
+ hf auth whoami >/dev/null
72
+ hf repos create --repo-type space --space-sdk docker --public --flavor cpu-basic --exist-ok "$repo"
73
+ hf upload --repo-type space --exclude "__pycache__/*" "$repo" "$ROOT/space" .
74
+ printf '\nSpace 页面 https://huggingface.co/spaces/%s\n' "$repo"
75
+ verify_space "$repo"
76
+ ;;
77
+ verify)
78
+ repo="${2:?请提供 Hugging Face 目标 Space,格式为 owner/space-name}"
79
+ verify_space "$repo"
80
+ ;;
81
+ *)
82
+ echo "用法: $0 {usage|colab [session-name]|publish owner/space-name|verify owner/space-name}" >&2
83
+ exit 2
84
+ ;;
85
+ esac
package/gpu-chat.sh ADDED
@@ -0,0 +1,88 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ gpu="${1:-L4}"
5
+ model="${2:-Qwen/Qwen2.5-0.5B-Instruct}"
6
+ port="${3:-8000}"
7
+ if [[ ! "$model" =~ ^[[:alnum:]_.-]+/[[:alnum:]_.-]+$ ||
8
+ ! "$port" =~ ^[1-9][0-9]{0,4}$ ]] ||
9
+ (( port > 65535 )); then
10
+ echo "用法: $0 [GPU] [owner/model] [local-port]" >&2
11
+ exit 2
12
+ fi
13
+
14
+ if command -v lsof >/dev/null &&
15
+ lsof -nP -iTCP:"$port" -sTCP:LISTEN >/dev/null 2>&1; then
16
+ echo "本地端口 $port 已被占用,请换一个端口。" >&2
17
+ exit 1
18
+ fi
19
+
20
+ colab="$(command -v "${COLAB_BIN:-colab}")"
21
+ if [[ "${COLAB_USAGE_CHECKED:-}" != 1 ]]; then
22
+ "$colab" usage
23
+ fi
24
+ session="hf-chat-$(date +%s)-$$"
25
+ scratch="$(mktemp -d)"
26
+ created=0
27
+ ssh_pid=""
28
+ cleanup() {
29
+ if [[ -n "$ssh_pid" ]]; then
30
+ kill "$ssh_pid" 2>/dev/null || true
31
+ wait "$ssh_pid" 2>/dev/null || true
32
+ fi
33
+ rm -rf -- "$scratch"
34
+ if [[ "$created" == 1 ]]; then
35
+ "$colab" stop -s "$session" || echo "请手动停止 Colab 会话 $session" >&2
36
+ fi
37
+ }
38
+ trap cleanup EXIT
39
+ trap 'exit 130' INT
40
+ trap 'exit 143' TERM
41
+ trap 'exit 129' HUP
42
+
43
+ ssh-keygen -q -t ed25519 -N '' -f "$scratch/key"
44
+ "$colab" new -s "$session" --gpu "$gpu"
45
+ created=1
46
+
47
+ # Each argument is shell-escaped before embedding it in the OpenSSH proxy command.
48
+ proxy="$(printf '%q ' "$colab" ssh --proxy-mode -s "$session" -i "$scratch/key")"
49
+ printf 'Colab 会话 %s,模型 %s。正在启动 vLLM,等待本地端口 %s 就绪。\n' \
50
+ "$session" "$model" "$port"
51
+ ssh -F /dev/null -T -i "$scratch/key" \
52
+ -o IdentitiesOnly=yes \
53
+ -o "ProxyCommand=$proxy" \
54
+ -o "UserKnownHostsFile=$scratch/known_hosts" \
55
+ -o StrictHostKeyChecking=accept-new \
56
+ -o ExitOnForwardFailure=yes \
57
+ -o ServerAliveInterval=30 -o ServerAliveCountMax=3 \
58
+ -L "127.0.0.1:$port:127.0.0.1:8000" \
59
+ root@colab-runtime bash -s -- "$model" <<'REMOTE' &
60
+ set -euo pipefail
61
+ nvidia-smi
62
+ python -m pip install --quiet uv
63
+ python -m uv venv /tmp/hf-chat
64
+ python -m uv pip install --python /tmp/hf-chat/bin/python --torch-backend auto vllm
65
+ exec /tmp/hf-chat/bin/vllm serve "$1" \
66
+ --host 127.0.0.1 --port 8000 --dtype half \
67
+ --max-model-len 4096 --served-model-name "$1"
68
+ REMOTE
69
+
70
+ ssh_pid=$!
71
+ base_url="http://127.0.0.1:$port/v1"
72
+ deadline=$((SECONDS + 600))
73
+ while kill -0 "$ssh_pid" 2>/dev/null; do
74
+ if models="$(curl --noproxy '*' -fs --max-time 3 "$base_url/models")" &&
75
+ printf '%s' "$models" | grep -Fq "\"$model\""; then
76
+ printf '\nAPI 已就绪\nBase URL %s\n模型 %s\nAPI Key 客户端必填时填 local\n按 Ctrl+C 停止并释放 GPU。\n\n' "$base_url" "$model"
77
+ wait "$ssh_pid"
78
+ exit
79
+ fi
80
+ if (( SECONDS >= deadline )); then
81
+ echo "等待 API 就绪超过 10 分钟,即将释放 GPU。" >&2
82
+ exit 1
83
+ fi
84
+ sleep 3
85
+ done
86
+ wait "$ssh_pid"
87
+ echo "SSH 已结束,API 未就绪。" >&2
88
+ exit 1
package/package.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "name": "colab-hf-chat",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Run Hugging Face chat models on Colab GPUs with vLLM, a localhost OpenAI-compatible API, and Colab compute-unit reporting.",
5
+ "bin": {
6
+ "colab-hf-chat": "cli.cjs"
7
+ },
8
+ "engines": {
9
+ "node": ">=18"
10
+ },
11
+ "files": [
12
+ "cli.cjs",
13
+ "wizard.sh",
14
+ "gpu-chat.sh",
15
+ "deploy.sh",
16
+ "space/"
17
+ ]
18
+ }
@@ -0,0 +1,9 @@
1
+ FROM python:3.12-slim
2
+ RUN useradd --create-home --uid 1000 user
3
+ WORKDIR /home/user/app
4
+ COPY requirements.txt .
5
+ RUN pip install --no-cache-dir -r requirements.txt
6
+ USER user
7
+ COPY --chown=user:user app.py model.py ./
8
+ EXPOSE 7860
9
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
@@ -0,0 +1,7 @@
1
+ ---
2
+ title: HF Text Classification API
3
+ sdk: docker
4
+ app_port: 7860
5
+ ---
6
+
7
+ Use `/docs` to try the API or send `POST /predict` with a JSON body containing `text`.
package/space/app.py ADDED
@@ -0,0 +1,29 @@
1
+ from contextlib import asynccontextmanager
2
+
3
+ from fastapi import FastAPI
4
+ from pydantic import BaseModel, Field
5
+
6
+ from model import Classifier
7
+
8
+
9
+ @asynccontextmanager
10
+ async def lifespan(app):
11
+ app.state.model = Classifier()
12
+ yield
13
+
14
+
15
+ app = FastAPI(title="Hugging Face Text Classification", lifespan=lifespan)
16
+
17
+
18
+ class PredictionRequest(BaseModel):
19
+ text: str = Field(min_length=1, max_length=4096)
20
+
21
+
22
+ @app.get("/health")
23
+ def health():
24
+ return {"status": "ready", "model": app.state.model.model_id}
25
+
26
+
27
+ @app.post("/predict")
28
+ def predict(request: PredictionRequest):
29
+ return app.state.model.predict(request.text)
package/space/model.py ADDED
@@ -0,0 +1,48 @@
1
+ import json
2
+ import os
3
+
4
+ import numpy as np
5
+ import onnxruntime as ort
6
+ from huggingface_hub import hf_hub_download
7
+ from tokenizers import Tokenizer
8
+
9
+ DEFAULT_MODEL = "Xenova/distilbert-base-uncased-finetuned-sst-2-english"
10
+ DEFAULT_REVISION = "0b6928efcb76139cae2c6881d49cda67fe119f42"
11
+
12
+
13
+ class Classifier:
14
+ def __init__(self):
15
+ self.model_id = os.getenv("MODEL_ID", DEFAULT_MODEL)
16
+ revision = os.getenv("MODEL_REVISION") or (
17
+ DEFAULT_REVISION if self.model_id == DEFAULT_MODEL else None
18
+ )
19
+ model_file = os.getenv("MODEL_FILE", "onnx/model_quantized.onnx")
20
+ tokenizer_path = hf_hub_download(self.model_id, "tokenizer.json", revision=revision)
21
+ config_path = hf_hub_download(self.model_id, "config.json", revision=revision)
22
+ with open(config_path, encoding="utf-8") as config:
23
+ self.labels = json.load(config)["id2label"]
24
+ self.tokenizer = Tokenizer.from_file(tokenizer_path)
25
+ self.tokenizer.enable_truncation(max_length=256)
26
+ options = ort.SessionOptions()
27
+ options.intra_op_num_threads = 2
28
+ self.session = ort.InferenceSession(
29
+ hf_hub_download(self.model_id, model_file, revision=revision),
30
+ sess_options=options,
31
+ providers=["CPUExecutionProvider"],
32
+ )
33
+
34
+ def predict(self, text):
35
+ encoded = self.tokenizer.encode(text)
36
+ inputs = {
37
+ "input_ids": encoded.ids,
38
+ "attention_mask": encoded.attention_mask,
39
+ "token_type_ids": encoded.type_ids,
40
+ }
41
+ logits = self.session.run(None, {
42
+ item.name: np.asarray([inputs[item.name]], dtype=np.int64)
43
+ for item in self.session.get_inputs()
44
+ })[0][0]
45
+ scores = np.exp(logits - logits.max())
46
+ scores /= scores.sum()
47
+ index = int(scores.argmax())
48
+ return {"model": self.model_id, "label": self.labels[str(index)], "score": float(scores[index])}
@@ -0,0 +1,5 @@
1
+ huggingface_hub>=0.34,<3
2
+ tokenizers>=0.21,<1
3
+ onnxruntime>=1.22,<2
4
+ fastapi>=0.116,<1
5
+ uvicorn>=0.35,<1
package/wizard.sh ADDED
@@ -0,0 +1,44 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ cd "$(dirname "$0")"
4
+ export PATH="$PATH:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin"
5
+
6
+ if ! command -v colab >/dev/null; then
7
+ if ! command -v uv >/dev/null; then
8
+ printf '首次运行需要 uv 来安装 Google Colab CLI。\n'
9
+ read -r -p '从 Astral 官方站点下载并安装 uv?[y/N] ' answer
10
+ case "$answer" in
11
+ y|Y) curl -fsSL https://astral.sh/uv/install.sh | env UV_NO_MODIFY_PATH=1 UV_INSTALL_DIR="$HOME/.local/bin" sh ;;
12
+ *) exit 0 ;;
13
+ esac
14
+ fi
15
+ echo '正在安装 Google Colab CLI…'
16
+ uv tool install google-colab-cli
17
+ export PATH="$(uv tool dir --bin):$PATH"
18
+ fi
19
+
20
+ printf '\n首次使用时,打开 CLI 打印的 Google 链接,用 Google AI Pro 账号授权,再把授权码粘贴回此处。\n'
21
+ colab usage
22
+ if [[ "${1:-}" == usage ]]; then
23
+ exit 0
24
+ fi
25
+ for tool in ssh ssh-keygen curl; do
26
+ if ! command -v "$tool" >/dev/null; then
27
+ echo "请先在当前系统安装 $tool。Ubuntu/WSL 可运行 sudo apt install openssh-client curl。" >&2
28
+ exit 1
29
+ fi
30
+ done
31
+ printf '\n请输入公开的 Hugging Face 聊天模型 ID。\n'
32
+ while true; do
33
+ read -r -p '模型 ID [Qwen/Qwen2.5-0.5B-Instruct]: ' model
34
+ model="${model:-Qwen/Qwen2.5-0.5B-Instruct}"
35
+ if [[ "$model" =~ ^[[:alnum:]_.-]+/[[:alnum:]_.-]+$ ]]; then
36
+ break
37
+ fi
38
+ echo '请输入 owner/model 格式的模型 ID。'
39
+ done
40
+
41
+ read -r -p 'GPU [L4,可填 T4/G4/A100/H100]: ' gpu
42
+ read -r -p '本地端口 [8000]: ' port
43
+ export COLAB_USAGE_CHECKED=1
44
+ exec ./gpu-chat.sh "${gpu:-L4}" "$model" "${port:-8000}"