故障排查指南
1. 故障排查概述
1.1 排查流程
当AI UI生成系统出现问题时,建议按照以下流程进行排查:
1.2 日志位置
系统日志文件位置:
| 组件 | 日志路径 | 描述 |
|---|---|---|
| 主应用 | logs/ai-ui-system.log | 应用主日志 |
| API服务 | logs/api.log | API请求日志 |
| 模型训练 | logs/training.log | 训练过程日志 |
| 数据生成 | logs/data_generation.log | 数据生成日志 |
| Docker容器 | docker logs ai-ui-system | 容器运行日志 |
| Nginx | /var/log/nginx/error.log | Web服务器日志 |
1.3 监控指标
关键监控指标:
| 指标 | 正常范围 | 异常表现 | 可能原因 |
|---|---|---|---|
| CPU使用率 | < 80% | > 90% | 计算密集、死循环 |
| 内存使用率 | < 85% | > 95% | 内存泄漏、数据过大 |
| GPU使用率 | 60-90% | < 30% 或 > 95% | 模型未加载、过载 |
| 响应时间 | < 3秒 | > 10秒 | 模型推理慢、资源不足 |
| 错误率 | < 5% | > 20% | 配置错误、资源不足 |
2. 常见问题与解决方案
2.1 数据生成问题
问题1:数据生成失败
症状:
ERROR: 数据生成失败
Traceback (most recent call last):
File "data/generate_synthetic_data.py", line 123, in <module>
dataset = generator.generate_dataset(args.num_samples)
File "data/generate_synthetic_data.py", line 45, in generate_dataset
prompt = self._generate_prompt(page_type, theme, variation)
KeyError: 'home'
原因分析:
- 页面类型配置错误
- 模板文件损坏
- 配置文件格式错误
解决方案:
检查配置文件:
# 验证YAML格式 python -c "import yaml; yaml.safe_load(open('config/model_config.yaml'))"检查页面类型:
# 验证页面类型配置 from data.generate_synthetic_data import UIDataGenerator generator = UIDataGenerator() print("支持的页面类型:", generator.page_types)重新生成数据:
# 删除旧数据 rm -rf data/synthetic/* # 重新生成 python data/generate_synthetic_data.py --output_dir data/synthetic --num_samples 100
问题2:数据格式错误
症状:
ERROR: JSON格式错误
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 45 (char 44)
解决方案:
验证JSON格式:
# 检查JSONL文件格式 python -c " import json with open('data/synthetic/train.jsonl', 'r') as f: for i, line in enumerate(f): try: json.loads(line) except json.JSONDecodeError as e: print(f'Line {i+1}: {e}') "修复数据格式:
# 数据修复脚本 import json def fix_jsonl_file(file_path): fixed_lines = [] with open(file_path, 'r', encoding='utf-8') as f: for line_num, line in enumerate(f, 1): try: json.loads(line) fixed_lines.append(line) except json.JSONDecodeError as e: print(f"修复第{line_num}行: {e}") # 尝试修复常见问题 fixed_line = line.replace('\\n', '\\n').replace('\\t', '\\t') try: json.loads(fixed_line) fixed_lines.append(fixed_line) except: print(f"无法修复第{line_num}行,跳过") # 写回修复后的文件 with open(file_path, 'w', encoding='utf-8') as f: f.writelines(fixed_lines) fix_jsonl_file('data/synthetic/train.jsonl')
问题3:内存不足
症状:
MemoryError: Unable to allocate array
解决方案:
减少样本数量:
# 分批生成数据 python data/generate_synthetic_data.py --output_dir data/synthetic --num_samples 1000优化内存使用:
# 修改数据生成器,使用生成器模式 def generate_dataset_streaming(self, num_samples: int): """流式生成数据集,减少内存使用""" for i in range(num_samples): yield self._generate_single_sample(i)
2.2 模型训练问题
问题1:CUDA内存溢出
症状:
RuntimeError: CUDA out of memory. Tried to allocate 2.00 GiB (GPU 0; 7.79 GiB total capacity; 5.12 GiB already allocated; 1.67 GiB free; 5.12 GiB reserved in total by PyTorch)
解决方案:
减少批次大小:
# config/model_config.yaml training: batch_size: 2 # 从4减少到2 gradient_accumulation_steps: 8 # 增加梯度累积启用混合精度训练:
training: fp16: true # 启用半精度训练清理GPU内存:
# 在训练脚本中添加 import torch torch.cuda.empty_cache()使用CPU训练:
# 设置环境变量 export CUDA_VISIBLE_DEVICES="" python train/finetune_lora.py --model_name google/flan-t5-base
问题2:训练不收敛
症状:
- 损失值不下降
- 生成质量没有改善
- 验证集准确率停滞
解决方案:
调整学习率:
training: learning_rate: 1e-4 # 降低学习率 warmup_steps: 200 # 增加预热步数检查数据质量:
# 数据质量检查脚本 def check_data_quality(train_file): with open(train_file, 'r') as f: for i, line in enumerate(f): if i >= 10: # 只检查前10个样本 break sample = json.loads(line) print(f"样本 {i+1}:") print(f" 指令: {sample['instruction'][:100]}...") print(f" 输出长度: {len(sample['output_json_minified'])}") print()增加训练轮数:
training: num_epochs: 5 # 从3增加到5调整LoRA参数:
lora: r: 32 # 增加秩 lora_alpha: 64 # 相应调整alpha
问题3:模型保存失败
症状:
OSError: [Errno 28] No space left on device
解决方案:
检查磁盘空间:
df -h du -sh models/清理旧模型:
# 删除旧的检查点 find models/ -name "checkpoint-*" -type d -mtime +7 -exec rm -rf {} \;使用外部存储:
# 将模型保存到外部存储 python train/finetune_lora.py --output_dir /external/models/ui-dsl-lora
问题4:GPU不可用
症状:
RuntimeError: No CUDA GPUs are available
解决方案:
检查GPU状态:
nvidia-smi检查CUDA安装:
import torch print(f"CUDA available: {torch.cuda.is_available()}") print(f"CUDA version: {torch.version.cuda}") print(f"GPU count: {torch.cuda.device_count()}")重新安装CUDA:
# 安装CUDA工具包 wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/cuda-ubuntu2004.pin sudo mv cuda-ubuntu2004.pin /etc/apt/preferences.d/cuda-repository-pin-600 sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/7fa2af80.pub sudo add-apt-repository "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/ /" sudo apt update sudo apt install cuda
2.3 模型推理问题
问题1:模型加载失败
症状:
OSError: [Errno 2] No such file or directory: 'models/ui-dsl-lora'
解决方案:
检查模型路径:
ls -la models/重新训练模型:
python train/finetune_lora.py \ --model_name google/flan-t5-base \ --train_file data/synthetic/train.jsonl \ --val_file data/synthetic/val.jsonl \ --output_dir models/ui-dsl-lora使用规则生成:
python inference/generate_ui.py \ --prompt "黑金风格的电商首页" \ --output output/ui_design.json \ --use_rules
问题2:推理超时
症状:
TimeoutError: Request timeout
解决方案:
增加超时时间:
# config/model_config.yaml api: timeout: 600 # 增加到10分钟优化模型配置:
model: max_length: 256 # 减少最大长度 temperature: 0.7 # 降低温度使用GPU加速:
export CUDA_VISIBLE_DEVICES=0
问题3:JSON解析失败
症状:
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
解决方案:
检查模型输出:
# 调试脚本 from inference.generate_ui import UIGenerator generator = UIGenerator() result = generator.generate("黑金风格的电商首页") print("原始输出:", repr(result["raw_output"]))启用规则回退:
# 在UIGenerator中启用规则回退 def generate(self, prompt: str, use_model: bool = True) -> Dict[str, Any]: try: if use_model and self.model is not None: generated_text = self.generate_with_model(prompt) else: generated_text = self.generate_with_rules(prompt) # 尝试解析JSON try: dsl = json.loads(generated_text) return {"success": True, "dsl": dsl, "method": "model"} except json.JSONDecodeError: # 使用规则回退 generated_text = self.generate_with_rules(prompt) dsl = json.loads(generated_text) return {"success": True, "dsl": dsl, "method": "rules_fallback"} except Exception as e: return {"success": False, "error": str(e)}
问题4:规则回退触发
症状:
WARNING: 模型输出JSON解析失败,使用规则回退
解决方案:
检查模型质量:
# 模型质量评估 def evaluate_model_quality(model_path, test_data): generator = UIGenerator() generator.load_model(model_path) success_count = 0 total_count = len(test_data) for sample in test_data: result = generator.generate(sample["instruction"]) if result["success"] and result["method"] == "model": success_count += 1 print(f"模型成功率: {success_count/total_count:.2%}")重新训练模型:
# 使用更多数据重新训练 python train/finetune_lora.py \ --model_name google/flan-t5-base \ --train_file data/synthetic/train.jsonl \ --val_file data/synthetic/val.jsonl \ --output_dir models/ui-dsl-lora \ --epochs 5
2.4 渲染问题
问题1:图片渲染失败
症状:
PIL.UnidentifiedImageError: cannot identify image file
解决方案:
检查字体文件:
# 字体检查脚本 from PIL import ImageFont def check_fonts(): font_paths = [ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf" ] for font_path in font_paths: try: font = ImageFont.truetype(font_path, 16) print(f"字体加载成功: {font_path}") except Exception as e: print(f"字体加载失败: {font_path} - {e}")安装字体:
# Ubuntu/Debian sudo apt-get install fonts-dejavu-core # CentOS/RHEL sudo yum install dejavu-sans-fonts使用默认字体:
# 修改字体加载逻辑 def _load_fonts(self): fonts = {} try: # 尝试加载系统字体 fonts["small"] = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 12) # ... 其他字体 except: # 回退到默认字体 fonts["small"] = ImageFont.load_default() fonts["medium"] = ImageFont.load_default() fonts["large"] = ImageFont.load_default() fonts["title"] = ImageFont.load_default() return fonts
问题2:字体加载失败
症状:
OSError: cannot open resource
解决方案:
检查字体路径:
find /usr/share/fonts -name "*.ttf" | grep -i dejavu下载字体文件:
# 下载DejaVu字体 wget https://github.com/dejavu-fonts/dejavu-fonts/archive/master.zip unzip master.zip sudo cp dejavu-fonts-master/ttf/*.ttf /usr/share/fonts/truetype/dejavu/ sudo fc-cache -fv使用Web字体:
# 使用Google Fonts import requests def download_font(font_name, font_size): url = f"https://fonts.googleapis.com/css2?family={font_name}:wght@400;700&display=swap" # 下载并缓存字体 pass
问题3:Vue模板错误
症状:
jinja2.exceptions.TemplateSyntaxError: unexpected char '}' at 1
解决方案:
检查模板语法:
# 模板验证脚本 from jinja2 import Template def validate_template(template_string): try: Template(template_string) print("模板语法正确") except Exception as e: print(f"模板语法错误: {e}")修复模板变量:
# 修复模板中的变量引用 def fix_template_variables(template_string): # 修复常见的模板变量问题 fixed = template_string.replace("{{", "{{ ") fixed = fixed.replace("}}", " }}") return fixed
2.5 API服务问题
问题1:服务启动失败
症状:
ERROR: [Errno 98] Address already in use
解决方案:
检查端口占用:
# 查看端口占用 lsof -i :8000 netstat -tulpn | grep :8000杀死占用进程:
# 杀死占用8000端口的进程 sudo kill -9 $(lsof -t -i:8000)使用不同端口:
# 使用不同端口启动 uvicorn api.main:app --host 0.0.0.0 --port 8001
问题2:端口占用
症状:
OSError: [Errno 98] Address already in use
解决方案:
查找占用进程:
sudo lsof -i :8000修改配置:
# config/model_config.yaml api: port: 8001 # 使用不同端口重启服务:
# 重启Docker服务 docker-compose -f docker/docker-compose.yml restart
问题3:请求超时
症状:
httpx.TimeoutException: Request timeout
解决方案:
增加超时时间:
api: timeout: 600 # 增加到10分钟优化模型推理:
model: max_length: 256 # 减少序列长度 temperature: 0.7 # 降低温度使用异步处理:
# 实现异步处理 import asyncio async def async_generate_ui(prompt: str): # 异步处理逻辑 pass
问题4:内存泄漏
症状:
- 内存使用持续增长
- 系统响应变慢
- 最终导致OOM
解决方案:
监控内存使用:
import psutil import gc def monitor_memory(): process = psutil.Process() memory_info = process.memory_info() print(f"内存使用: {memory_info.rss / 1024 / 1024:.2f} MB") def cleanup_memory(): gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache()定期清理内存:
# 在API端点中添加内存清理 @app.post("/generate-ui") async def generate_ui(request: GenerateUIRequest): try: result = ui_generator.generate(request.prompt) return result finally: # 清理内存 cleanup_memory()
2.6 Docker部署问题
问题1:镜像构建失败
症状:
ERROR: failed to solve: failed to compute cache key: failed to calculate checksum of ref
解决方案:
清理Docker缓存:
docker system prune -a docker builder prune重新构建镜像:
docker build --no-cache -t ai-ui-system:latest -f docker/Dockerfile .检查Dockerfile:
# 确保Dockerfile语法正确 FROM python:3.10-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD ["python", "api/main.py"]
问题2:容器启动失败
症状:
ERROR: Container 'ai-ui-system' exited with code 1
解决方案:
查看容器日志:
docker logs ai-ui-system检查配置文件:
# 检查配置文件是否存在 docker run --rm -v $(pwd)/config:/app/config ai-ui-system ls -la /app/config/修复权限问题:
# 修复文件权限 chmod +x data/generate_synthetic_data.py chmod +x train/finetune_lora.py chmod +x inference/generate_ui.py
问题3:网络连接问题
症状:
ERROR: Connection refused
解决方案:
检查网络配置:
# 检查Docker网络 docker network ls docker network inspect ai-ui-network修复端口映射:
# docker-compose.yml services: ai-ui-system: ports: - "8000:8000" # 确保端口映射正确重启网络:
docker-compose -f docker/docker-compose.yml down docker-compose -f docker/docker-compose.yml up -d
问题4:卷挂载失败
症状:
ERROR: Mount denied
解决方案:
检查卷路径:
# 确保路径存在 mkdir -p output/images output/vue output/dsl mkdir -p models logs修复权限:
# 修复目录权限 sudo chown -R $USER:$USER output/ models/ logs/ chmod -R 755 output/ models/ logs/使用绝对路径:
# docker-compose.yml volumes: - /absolute/path/to/output:/app/output - /absolute/path/to/models:/app/models
3. 调试工具和技巧
3.1 日志分析
查看实时日志:
# 查看应用日志
tail -f logs/ai-ui-system.log
# 查看Docker日志
docker logs -f ai-ui-system
# 查看Nginx日志
tail -f /var/log/nginx/error.log
日志分析脚本:
# 日志分析工具
import re
from collections import Counter
def analyze_logs(log_file):
"""分析日志文件"""
error_patterns = []
error_counts = Counter()
with open(log_file, 'r') as f:
for line in f:
if 'ERROR' in line:
# 提取错误信息
error_match = re.search(r'ERROR: (.+)', line)
if error_match:
error = error_match.group(1)
error_patterns.append(error)
error_counts[error] += 1
print("错误统计:")
for error, count in error_counts.most_common(10):
print(f" {error}: {count}次")
return error_patterns
# 使用示例
analyze_logs('logs/ai-ui-system.log')
3.2 性能分析工具
CPU性能分析:
import cProfile
import pstats
def profile_function(func, *args, **kwargs):
"""分析函数性能"""
profiler = cProfile.Profile()
profiler.enable()
result = func(*args, **kwargs)
profiler.disable()
stats = pstats.Stats(profiler)
stats.sort_stats('cumulative')
stats.print_stats(10)
return result
# 使用示例
profile_function(ui_generator.generate, "黑金风格的电商首页")
内存分析:
import tracemalloc
import psutil
def memory_profiler():
"""内存分析器"""
tracemalloc.start()
# 执行需要分析的代码
result = ui_generator.generate("黑金风格的电商首页")
# 获取内存快照
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
print("内存使用统计:")
for stat in top_stats[:10]:
print(stat)
# 获取进程内存信息
process = psutil.Process()
memory_info = process.memory_info()
print(f"进程内存使用: {memory_info.rss / 1024 / 1024:.2f} MB")
tracemalloc.stop()
# 使用示例
memory_profiler()
3.3 网络调试
API测试工具:
import requests
import time
def test_api_endpoints(base_url):
"""测试API端点"""
endpoints = [
"/health",
"/templates",
"/themes"
]
for endpoint in endpoints:
try:
start_time = time.time()
response = requests.get(f"{base_url}{endpoint}", timeout=10)
duration = time.time() - start_time
print(f"{endpoint}: {response.status_code} ({duration:.2f}s)")
except Exception as e:
print(f"{endpoint}: ERROR - {e}")
# 使用示例
test_api_endpoints("http://localhost:8000")
负载测试:
import asyncio
import aiohttp
import time
async def load_test(base_url, num_requests=100, concurrency=10):
"""负载测试"""
semaphore = asyncio.Semaphore(concurrency)
async def make_request(session):
async with semaphore:
start_time = time.time()
try:
async with session.post(
f"{base_url}/generate-ui",
json={"prompt": "测试Prompt", "output_format": "json"}
) as response:
duration = time.time() - start_time
return response.status, duration
except Exception as e:
duration = time.time() - start_time
return 500, duration
async with aiohttp.ClientSession() as session:
tasks = [make_request(session) for _ in range(num_requests)]
results = await asyncio.gather(*tasks)
# 分析结果
status_codes = [r[0] for r in results]
durations = [r[1] for r in results]
print(f"总请求数: {num_requests}")
print(f"成功率: {status_codes.count(200) / num_requests:.2%}")
print(f"平均响应时间: {sum(durations) / len(durations):.2f}s")
print(f"最大响应时间: {max(durations):.2f}s")
print(f"最小响应时间: {min(durations):.2f}s")
# 使用示例
asyncio.run(load_test("http://localhost:8000"))
4. 监控和告警
4.1 关键指标监控
系统指标监控:
import psutil
import time
import json
class SystemMonitor:
def __init__(self):
self.metrics = []
def collect_metrics(self):
"""收集系统指标"""
metrics = {
"timestamp": time.time(),
"cpu_percent": psutil.cpu_percent(),
"memory_percent": psutil.virtual_memory().percent,
"disk_percent": psutil.disk_usage('/').percent,
"load_average": psutil.getloadavg()[0]
}
if psutil.WINDOWS:
metrics["gpu_memory"] = 0 # Windows需要额外库
else:
try:
import torch
if torch.cuda.is_available():
metrics["gpu_memory"] = torch.cuda.memory_allocated() / 1024**3
except ImportError:
metrics["gpu_memory"] = 0
self.metrics.append(metrics)
return metrics
def check_alerts(self, metrics):
"""检查告警条件"""
alerts = []
if metrics["cpu_percent"] > 90:
alerts.append("CPU使用率过高")
if metrics["memory_percent"] > 90:
alerts.append("内存使用率过高")
if metrics["disk_percent"] > 90:
alerts.append("磁盘使用率过高")
if metrics["load_average"] > 10:
alerts.append("系统负载过高")
return alerts
# 使用示例
monitor = SystemMonitor()
metrics = monitor.collect_metrics()
alerts = monitor.check_alerts(metrics)
if alerts:
print("告警:", ", ".join(alerts))
4.2 告警配置
告警规则配置:
# alerts.yaml
alerts:
- name: "高CPU使用率"
condition: "cpu_percent > 90"
duration: "5m"
severity: "warning"
message: "CPU使用率超过90%"
- name: "高内存使用率"
condition: "memory_percent > 90"
duration: "2m"
severity: "critical"
message: "内存使用率超过90%"
- name: "服务不可用"
condition: "health_check_failed"
duration: "1m"
severity: "critical"
message: "服务健康检查失败"
告警发送:
import smtplib
from email.mime.text import MIMEText
class AlertSender:
def __init__(self, smtp_server, smtp_port, username, password):
self.smtp_server = smtp_server
self.smtp_port = smtp_port
self.username = username
self.password = password
def send_alert(self, alert_message, recipients):
"""发送告警邮件"""
msg = MIMEText(alert_message)
msg['Subject'] = "AI UI系统告警"
msg['From'] = self.username
msg['To'] = ", ".join(recipients)
try:
server = smtplib.SMTP(self.smtp_server, self.smtp_port)
server.starttls()
server.login(self.username, self.password)
server.send_message(msg)
server.quit()
print("告警邮件发送成功")
except Exception as e:
print(f"告警邮件发送失败: {e}")
# 使用示例
alert_sender = AlertSender(
smtp_server="smtp.gmail.com",
smtp_port=587,
username="your-email@gmail.com",
password="your-password"
)
alert_sender.send_alert(
"AI UI系统CPU使用率过高",
["admin@company.com"]
)
5. 紧急处理流程
5.1 服务宕机处理
立即响应步骤:
确认服务状态:
# 检查服务状态 curl -f http://localhost:8000/health # 检查Docker容器状态 docker ps -a | grep ai-ui-system查看错误日志:
# 查看最新错误日志 tail -n 100 logs/ai-ui-system.log | grep ERROR # 查看Docker日志 docker logs --tail 100 ai-ui-system重启服务:
# 重启Docker服务 docker-compose -f docker/docker-compose.yml restart ai-ui-system # 或者完全重启 docker-compose -f docker/docker-compose.yml down docker-compose -f docker/docker-compose.yml up -d验证恢复:
# 等待服务启动 sleep 30 # 验证服务可用性 curl -f http://localhost:8000/health
5.2 数据恢复流程
备份检查:
# 检查备份文件
ls -la backups/
ls -la models/
ls -la data/synthetic/
数据恢复:
# 恢复模型文件
cp backups/models/ui-dsl-lora/* models/ui-dsl-lora/
# 恢复数据文件
cp backups/data/synthetic/* data/synthetic/
# 恢复配置文件
cp backups/config/* config/
验证恢复:
# 测试模型加载
python -c "from inference.generate_ui import UIGenerator; UIGenerator().load_model('models/ui-dsl-lora')"
# 测试数据完整性
python -c "import json; [json.loads(line) for line in open('data/synthetic/train.jsonl')]"
5.3 紧急回退方案
使用规则生成:
# 强制使用规则生成,绕过模型
python inference/generate_ui.py \
--prompt "黑金风格的电商首页" \
--output output/ui_design.json \
--use_rules
降级服务:
# 修改配置,降低服务复杂度
api:
workers: 1 # 减少工作进程
timeout: 60 # 减少超时时间
model:
max_length: 256 # 减少序列长度
temperature: 0.5 # 降低温度
临时禁用功能:
# 在API中临时禁用某些功能
@app.post("/generate-ui")
async def generate_ui(request: GenerateUIRequest):
# 临时只支持JSON格式
if request.output_format != "json":
raise HTTPException(status_code=400, detail="暂时只支持JSON格式")
# 强制使用规则生成
result = ui_generator.generate(request.prompt, use_model=False)
return result
通过以上故障排查指南,开发者可以快速定位和解决AI UI生成系统中的各种问题,确保系统的稳定运行。