资讯详情 TinyIMGRAG:基于 SDXL、Qwen2.5-VL 与 CLIP 检索的增强图像生成简化版 ImageRAG 实现
📅 2026/10/13 6:03:16
示例工程教程【免费下载链接】tiny-universe《大模型白盒子构建指南》一个全手搓的Tiny-Universe项目地址https://gitcode.com/datawhalechina/tiny-universe点击查看免费下载本文以 tiny-universe 仓库中的 TinyIMGRAG 模块为核心讲解如何在不依赖任何外部 API、仅用一张 24G 显存3090显卡的前提下搭建一个完整的简化版 ImageRAGIMGRAG流程先用 SDXL 生成初始图像再用 Qwen2.5-VL 评判图像与提示词是否一致、Qwen2.5 重写差异概念、CLIP 检索参考图像最后通过 IP-Adapter 图文联合生成增强图像。读完后你可以理解 T2I 幻觉问题的缓解思路并掌握“生成—评估—检索—再生成”这条反馈闭环的完整工程实现与显存管理技巧。1. 为什么需要 IMGRAGT2I 生成的一致性与幻觉问题常规 AIGC 生图模型如 Stable Diffusion 系列主要基于提示词进行指导生成。与 LLM 会出现幻觉一样Stable Diffusion 等图像生成模型同样存在一定程度的幻觉并且很难控制图像多次生成时的一致性。在文本到图像T2I生成领域AIGC 模型在处理未见过的概念、或者需要服从前后生图一致性时常常表现出局限性由于模型缺乏对特定视觉线索的充分学习生成结果在面对新颖或复杂概念时往往偏离目标。IMGRAGImage RAG的出发点是利用外部数据集中的图像数据来支撑图像生成的质量与提示词忠诚度本质上是把检索增强生成RAG的思想迁移到图像生成领域。它需要解决三个核心问题如何确定初始生成图像中缺失的概念如何获取与缺失概念匹配的图像如何利用获取的所有信息来生成符合预期的图像为此IMGRAG 通过动态选择能够补充模型缺失视觉信息的图像来提升生成模型的鲁棒性整体流程分为四步初始生成基于给定文本提示利用 T2I 生成模型生成一张初始图像匹配评估将生成的图像输入视觉语言模型VLM评估该图像是否与原始提示匹配检索与优化如果不匹配系统识别图像中缺失的概念并为每个缺失概念生成检索描述从外部图像数据库中检索相关图像将其作为额外上下文提供给生成模型结果生成整合检索到的图像信息最终生成更符合预期的新概念图像。IMGRAG 整体流程示意图源ImageRAG: Dynamic Image Retrieval for Reference-Guided Image Generation 论文TinyIMGRAG 正是这一思想的轻量化落地所有模型全程运行在一张 24G 的 3090 显卡上项目不调用任何外部 API只包含核心模块。2. 运行环境与模型准备2.1 基础环境原始文档给出的基础环境如下OSWindows 10CUDA 12.1Python 3.10从 GitHub 下载并安装 CLIP 包先安装requirements.txt中的包再安装 CLIP仓库中已经自带了 CLIP 的源码包位于 packages/CLIP-main 目录下。若从源码获取 CLIP 后按如下方式本地安装cd CLIP-main pip install -e .requirements.txt 中锁定的关键依赖版本可复现前提依赖包版本用途torch / torchvision / torchaudio2.2.1cu121 / 0.17.1cu121 / 2.2.1cu121CUDA 12.1 环境的深度学习框架transformers4.50.1Qwen2.5-VL / Qwen2.5 模型加载diffusers0.33.1SDXL 文本到图像管道含 IP-Adapter 接口modelscope1.24.0下载并加载 Qwen2.5 系列模型open_clip_torch2.29.0CLIP 生态支持qwen-vl-utils0.0.8Qwen-VL 视觉信息预处理process_vision_infoauto-gptq / optimum未锁版本加载 GPTQ-Int4 量化模型huggingface-hub0.29.3下载 IP-Adapter 权重安装顺序上需要注意先安装requirements.txt中的包再安装 CLIPCLIP 在 requirements.txt 末尾也以注释形式提示了这一点。2.2 模型下载与目录约定download_model.py 给出了四个模型的统一下载方式三个 Qwen 与 SDXL 模型通过 ModelScope 的snapshot_download拉取到./model/目录IP-Adapter 权重通过huggingface_hub.snapshot_download下载import modelscope import huggingface_hub model_dir modelscope.snapshot_download(Qwen/Qwen2.5-VL-3B-Instruct, cache_dir./model/, revisionmaster) model_dir modelscope.snapshot_download(Qwen/Qwen2.5-7B-Instruct-GPTQ-Int4, cache_dir./model/, revisionmaster) model_dir modelscope.snapshot_download(stabilityai/stable-diffusion-xl-base-1.0, cache_dir./model/, revisionmaster) model_dir huggingface_hub.snapshot_download(repo_idh94/IP-Adapter, local_dir./model/, max_workers1)结合各模块代码中的默认路径可以整理出完整的模型清单与目录约定模型目录约定相对 TinyIMGRAG 目录角色Stable Diffusion XL base./model/stabilityai/stable-diffusion-xl-base-1.0初始图像与增强图像生成IP-Adapterplus_sdxl_vit-h./model/h94/IP-Adapter参考图引导的图文联合生成Qwen2.5-VL-3B-Instruct./model/Qwen/Qwen2.5-VL-3B-Instruct评判图像与提示词的一致性Qwen2.5-7B-Instruct-GPTQ-Int4./model/Qwen/Qwen2.5-7B-Instruct-GPTQ-Int4差异概念分析与检索描述改写CLIP ViT-B-32 权重./model/ViT-B-32.pt文本—图像相似度检索其中 ViT-B-32.pt 需从 Hugging Face 上的 jinaai/clip-models 仓库单独下载放置到./model/下。检索语料库则使用仓库自带的 datasets/imgs 目录内置了 cradle.jpg、dog.jpg、oil_painting.png、classroom.jpg 等 13 张示例图片作为外部图像数据库。3. 初始图像生成SDXLGenerator 模块初始生成对应 IMGRAG/ImgGenerator.py 中的SDXLGenerator类。它基于 Stable Diffusion XLSDXL模型封装了模型加载、参数配置和图像生成的整个流程同时支持两种模式纯文本生成文生图和文本 参考图像引导的生成图文联合生图。class SDXLGenerator: def __init__(self, prompt, output_path, steps50, seed0, use_image_guidanceFalse, image_pathNone, ip_scale0.5, sd_path./model/stabilityai/stable-diffusion-xl-base-1.0, adapter_path./model/h94/IP-Adapter): self.prompt prompt self.output_path output_path self.steps steps self.seed seed self.use_image_guidance use_image_guidance self.image_path image_path self.ip_scale ip_scale # 设备设置 self.device cuda if torch.cuda.is_available() else cpu self.torch_dtype torch.float16 if self.device cuda else torch.float32 # 初始化管道 self.pipe AutoPipelineForText2Image.from_pretrained( sd_path, torch_dtypeself.torch_dtype ).to(self.device) # 如果需要使用图像引导加载图像编码器和IP-Adapter if self.use_image_guidance: # 初始化图像编码器 self.image_encoder CLIPVisionModelWithProjection.from_pretrained( adapter_path, subfoldermodels/image_encoder, torch_dtypeself.torch_dtype ).to(self.device) # 将图像编码器设置到管道中 self.pipe AutoPipelineForText2Image.from_pretrained( sd_path, image_encoderself.image_encoder, torch_dtypeself.torch_dtype ).to(self.device) # 加载IP-Adapter self.pipe.load_ip_adapter( adapter_path, subfoldersdxl_models, weight_nameip-adapter-plus_sdxl_vit-h.safetensors ) self.pipe.set_ip_adapter_scale(self.ip_scale) def generate_image(self): # 准备生成参数 generator torch.Generator(deviceself.device).manual_seed(self.seed) # 执行生成 print(开始生成...) if self.use_image_guidance: # 加载参考图像 ref_image Image.open(self.image_path) # 使用图像和文本生成 result self.pipe( promptself.prompt, ip_adapter_imageref_image, negative_promptmonochrome, lowres, bad anatomy, worst quality, low quality, num_inference_stepsself.steps, generatorgenerator, ) else: # 只使用文本生成 result self.pipe( promptself.prompt, negative_promptmonochrome, lowres, bad anatomy, worst quality, low quality, num_inference_stepsself.steps, generatorgenerator, ) # 保存结果 result.images[0].save(self.output_path) print(f生成完成结果已保存至: {self.output_path}) return self.output_path3.1 参数说明参数默认值说明prompt必填文本提示词output_path必填生成图像保存路径steps50采样步数seed0随机种子保证同一提示可复现use_image_guidanceFalseFalse 为纯文生图True 启用 IP-Adapter 图像引导image_pathNone参考图像路径use_image_guidanceTrue时必填ip_scale0.5IP-Adapter 权重强度控制参考图对生成结果的影响幅度sd_path./model/stabilityai/stable-diffusion-xl-base-1.0SDXL 基础模型本地路径adapter_path./model/h94/IP-AdapterIP-Adapter 权重本地路径3.2 源码细节解读该类采用模块化设计主要包含三个组件模型加载系统自动处理 SDXL 基础模型和 IP-Adapter 的加载。从源码看ImgGenerator.py当use_image_guidance为 True 时会先加载models/image_encoder子目录下的CLIPVisionModelWithProjection作为参考图编码器再重建管道并把该编码器注入随后通过load_ip_adapter加载ip-adapter-plus_sdxl_vit-h.safetensors权重文件并用set_ip_adapter_scale设定引导强度。这意味着同一个类通过use_image_guidance一个开关即可在“文生图”和“图文联合生图”之间切换设备管理自动检测 CUDA 是否可用GPU 上使用torch.float16半精度以节省显存CPU 回退到torch.float32生成 pipelinegenerate_image通过torch.Generator固定随机种子两条生成分支共用统一的负面提示词monochrome, lowres, bad anatomy, worst quality, low quality来过滤低质量结果生成后自动保存图像并返回路径。4. 匹配评估Qwen2.5-VL 判断图像与提示的一致性第二步是“匹配评估”。IMGRAG/ImgEvaluator.py 利用 Qwen2.5-VL 视觉语言模型处理第一步生成的图像和原始提示文本返回图像与提示之间的差异或一致性结论。它由两个函数组成load_qwen_vlm加载 Qwen-VL 模型和处理器。模型是处理图像和文本生成的核心处理器负责把输入数据图像和文本转换为模型可理解的格式run_qwen_vl执行具体的推理任务——把图像编码为 Base64构建包含图像与提示信息的消息结构经处理器预处理后送入模型推理最终输出指示图像与描述文本之间差异或一致性的结果。def load_qwen_vlm(pretrained_model./model/Qwen/Qwen2.5-VL-3B-Instruct): min_pixels 256 * 28 * 28 max_pixels 1280 * 28 * 28 # default: Load the model on the available device(s) model Qwen2_5_VLForConditionalGeneration.from_pretrained( pretrained_model, torch_dtypeauto, device_mapauto ) # default processer processor AutoProcessor.from_pretrained(pretrained_model, min_pixelsmin_pixels, max_pixelsmax_pixels) return model, processor def run_qwen_vl(image_path, prompt, model, processor): # 编码图片 with open(image_path, rb) as image_file: base64_image base64.b64encode(image_file.read()).decode(utf-8) messages [ { role: user, content: [ { type: image, image: fdata:image/jpeg;base64,{base64_image}, }, {type: text, text: fPlease identify the different between the image and the description of the {prompt}, and output in the format The different conception is a XX. If no inconsistent content are found, return Content matches.}, ], } ] # Preparation for inference text processor.apply_chat_template( messages, tokenizeFalse, add_generation_promptTrue ) image_inputs, video_inputs process_vision_info(messages) inputs processor( text[text], imagesimage_inputs, videosvideo_inputs, paddingTrue, return_tensorspt ) inputs inputs.to(cuda) # Inference: Generation of the output generated_ids model.generate(**inputs, max_new_tokens128, temperature0.01) generated_ids_trimmed [ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids) ] output_text processor.batch_decode( generated_ids_trimmed, skip_special_tokensTrue, clean_up_tokenization_spacesFalse ) return output_text[0]几个值得注意的实现细节像素预算min_pixels 256 * 28 * 28、max_pixels 1280 * 28 * 28限定了处理器缩放图像时的 token 数量上下界28×28 为 Qwen-VL 的视觉 patch 粒度既避免小图信息损失也防止大图挤爆显存输出协议提示词要求模型在发现不一致时按The different conception is a XX的格式输出差异概念若无不一致则返回固定标记Content matches。这个标记是后续流水线第 6 节run_pipeline判断“是否直接返回初始图”的分支依据属于模块间约定的协议字符串低温度解码temperature0.01、max_new_tokens128使评判输出尽量确定、简短从源码结构看模型通过modelscope的Qwen2_5_VLForConditionalGeneration与AutoProcessor加载并用qwen_vl_utils.process_vision_info解析消息中的图像输入这也是requirements.txt中锁定qwen-vl-utils0.0.8的原因。5. 概念改写Qwen2.5 LLM 重写差异文本第三步是把 VLM 输出的“口语化差异描述”改写成适合图像检索的概念性文本。IMGRAG/RewritePrompt.py 使用 Int4 量化的 Qwen2.5-7B-Instruct-GPTQ-Int4 完成这项工作——量化版 7B 模型在 24G 显卡上负担较轻是“全流程单卡”的关键选型之一。两个核心函数如下load_qwen_llm通过AutoModelForCausalLM加载模型支持torch_dtypeauto与device_mapauto自动完成设备映射AutoTokenizer加载分词器用于文本输入处理run_qwen_llm将系统提示与用户输入组合为消息列表经apply_chat_template转换后送入模型生成输出最后解码返回文本。def load_qwen_llm(model_name./model/Qwen/Qwen2.5-7B-Instruct-GPTQ-Int4): model AutoModelForCausalLM.from_pretrained( model_name, torch_dtypeauto, device_mapauto ) tokenizer AutoTokenizer.from_pretrained(model_name) return model, tokenizer def run_qwen_llm(prompt, model, tokenizer): messages [ {role: system, content: You are Qwen, created by Alibaba Cloud. You are a helpful assistant.}, {role: user, content: prompt} ] text tokenizer.apply_chat_template( messages, tokenizeFalse, add_generation_promptTrue ) model_inputs tokenizer([text], return_tensorspt).to(model.device) generated_ids model.generate( **model_inputs, max_new_tokens512, temperature0.01 ) generated_ids [ output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids) ] response tokenizer.batch_decode(generated_ids, skip_special_tokensTrue)[0] return response同样的低温度0.01解码策略保证了改写输出的确定性。该模块在流水线中承担两次不同职责一次是“分析并改写差异概念”要求输出A dog、A car A running man这类可用分隔的检索短语一次是“校验概念是否可用图像描述”只输出 True/False详见第 6 节。6. 图像向量化与 CLIP 检索第四步是“获取与缺失概念匹配的图像”。IMGRAG/ImgRetrieval.py 使用 CLIP 计算文本提示与图片之间的相似性由两个函数构成get_clip_similarities接受一组文本提示和图片路径先加载 CLIP 模型并计算文本特征然后分批处理图片、计算每张图片特征用torch.matmul计算余弦相似度返回与文本最相似的前 k 张图片路径与分数_get_image_embeddings负责加载或计算图像嵌入。若已有缓存clip_embeddings_b{batch_idx}.pt则直接读缓存否则通过 CLIP 编码图像并保存缓存到指定目录避免重复计算。def get_clip_similarities(prompts, image_paths, embeddings_path./datasets/vector_bases, bs2, k5, devicecuda:0, model_path./model/ViT-B-32.pt): Calculate similarity between text prompts and images using CLIP model. Args: prompts: List of text prompts to compare against images image_paths: List of paths to images embeddings_path: Directory to save/load precomputed image embeddings bs: Batch size for processing images k: Number of top similar images to return device: Device to run computations on model_path: Path to CLIP model weights Returns: Tuple of (top image paths, top similarity scores) sorted by similarity # Load CLIP model and preprocessing model, preprocess clip.load(model_path, devicedevice) text_tokens clip.tokenize(prompts).to(device) # Initialize result containers all_scores [] all_paths [] all_embeddings torch.empty((0, 512)).to(device) # Process in batches with torch.no_grad(): # Get text features once text_features model.encode_text(text_tokens) text_features torch.nn.functional.normalize(text_features, p2, dim1) # Process images in batches for batch_start in range(0, len(image_paths), bs): batch_end min(batch_start bs, len(image_paths)) batch_paths image_paths[batch_start:batch_end] # Try to load precomputed embeddings or compute new ones embeddings, valid_paths _get_image_embeddings( batch_paths, batch_start, model, preprocess, device, embeddings_path ) if embeddings is None: continue # Calculate similarities batch_scores torch.matmul(text_features, embeddings.T) batch_scores batch_scores.cpu().numpy().squeeze() # Update running totals if batch_scores.ndim 0: # 如果是标量 all_scores.append(batch_scores.item()) else: all_scores.extend(batch_scores.tolist()) all_paths.extend(valid_paths) all_embeddings torch.cat([all_embeddings, embeddings]) # Keep only top k results if len(all_scores) k: top_indices np.argsort(all_scores)[-k:] all_scores [all_scores[i] for i in top_indices] all_paths [all_paths[i] for i in top_indices] all_embeddings all_embeddings[top_indices] # Return sorted results (highest first) sorted_indices np.argsort(all_scores)[::-1] return [all_paths[i] for i in sorted_indices], [all_scores[i] for i in sorted_indices] def _get_image_embeddings(image_paths, batch_idx, model, preprocess, device, embeddings_path): Helper to get embeddings either from cache or by computing them cache_file os.path.join(embeddings_path, fclip_embeddings_b{batch_idx}.pt) # Try loading from cache if os.path.exists(cache_file): cached torch.load(cache_file, map_locationdevice) return cached[normalized_clip_embeddings], cached[paths] # Compute new embeddings images [] valid_paths [] for path in image_paths: try: img preprocess(Image.open(path)).unsqueeze(0).to(device) images.append(img) valid_paths.append(path) except Exception as e: print(fCouldnt read {path}: {str(e)}) continue if not images: return None, None images torch.cat(images) features model.encode_image(images) features torch.nn.functional.normalize(features, p2, dim1) # Save to cache if requested if embeddings_path: os.makedirs(embeddings_path, exist_okTrue) torch.save({ normalized_clip_embeddings: features, paths: valid_paths }, cache_file) return features, valid_paths参数与实现要点参数默认值说明prompts必填待比较的文本提示列表或字符串image_paths必填候选图片路径列表embeddings_path./datasets/vector_bases图像嵌入缓存目录按批保存clip_embeddings_b{batch_idx}.ptbs2图像处理的批大小小批量以控制显存峰值k5返回的 Top-k 图片数量devicecuda:0计算设备model_path./model/ViT-B-32.ptCLIP 权重路径从源码结构看这里有两处值得展开的设计余弦相似度的归一化实现文本特征与图像特征都先经过torch.nn.functional.normalize(p2, dim1)做 L2 归一化因此torch.matmul(text_features, embeddings.T)直接等价于余弦相似度且整个检索在torch.no_grad()下执行增量式 Top-k 剪枝每处理完一个批次如果累计数量超过k就用np.argsort(all_scores)[-k:]只保留当前分数最高的 k 条记录。这样无论候选库多大内存中都只保留 k 个嵌入512 维把检索开销从 O(N) 内存降到了 O(k)。此外_get_image_embeddings对单张图片读取异常做了 try/except 容错损坏图片会被打印跳过而不中断整个检索嵌入缓存ViT-B-32 的编码结果按批次缓存到embeddings_path下第二次运行同样的检索时可直接torch.load命中缓存跳过编码阶段。7. ImageRAGPipeline完整流程编排与显存管理前面四个模块最终由 main.py 中的ImageRAGPipeline类串联成一条自动化“生成—评估—检索—再生成”流水线。该类同时使用 SDXLGenerator 生成图像、Qwen 的 VLM 和 LLM 做图像评估与提示词分析改写、CLIP 做图像检索。7.1 懒加载与显存管理由于整个项目只使用一张 3090 显卡为了避免多模型同时驻留显存pipeline 采用了懒加载lazy loading策略各个模型VLM、LLM、CLIP初始时均为None在需要时才初始化并且每次初始化前都会先调用_cleanup_models释放已有模型def _initialize_vlm(self): Lazy loading of vision-language model with cleanup of previous models self._cleanup_models() # Clean up any existing models first if self.vl_model is None: self.vl_model, self.vl_processor load_qwen_vlm() print(VLM loaded on GPU) def _cleanup_models(self): Clean up all models to free GPU memory if self.vl_model is not None: del self.vl_model self.vl_model None print(VLM removed from GPU) if self.vl_processor is not None: del self.vl_processor self.vl_processor None if self.llm_model is not None: del self.llm_model self.llm_model None print(LLM removed from GPU) if self.llm_tokenizer is not None: del self.llm_tokenizer self.llm_tokenizer None if self.clip_model is not None: del self.clip_model self.clip_model None print(CLIP model removed from GPU) torch.cuda.empty_cache() print(GPU cache cleared)_initialize_llm、_initialize_clip采用相同模式。在代码的各个方法中还使用try/finally确保模型被清理例如evaluate_image_content在调用 VLM 后无论推理成功与否都会执行_cleanup_modelsgenerate_initial_image与generate_enhanced_image在生成图像前后也各清理一次确保 SDXL 采样显存占用最高的阶段过程中显存充足。这种“同一时刻 GPU 上只驻留一个重型模型”的设计是本项目能在 24G 单卡上串行跑通 SDXL 3B VLM 7B LLM CLIP 的前提。7.2 六步流水线 run_pipeline各方法的职责可以整理为方法依赖模型作用generate_initial_image(prompt, seed0, steps50)SDXL纯文本模式生成initial_image.pngevaluate_image_content(image_path, prompt)Qwen2.5-VL输出差异描述或Content matchesanalyze_mismatch_concepts(vlm_feedback)Qwen2.5 LLM把差异描述改写成分隔的检索概念validate_concepts(concept_texts)Qwen2.5 LLM逐个校验概念是否可用图像描述True/Falseretrieve_reference_images(concepts, image_dir./datasets/imgs)CLIP检索最相似的参考图generate_enhanced_image(prompt, reference_image_path, seed0, steps50, ip_scale0.5)SDXL IP-Adapter图文联合生成enhanced_image.png其中概念改写的提示词见 main.py要求 LLM 用“名词或带形容词/副词修饰的名词”来描述概念格式如A dog、A oil-painting style、A car A running man且明确禁止输出A different conception这类无检索价值的短语校验概念时则用简单的 True/False 判断概念是否“可以用一张图像来描述”。run_pipeline组织了完整流程并内置了三处“提前返回初始图”的兜底分支评估匹配、无有效概念、无检索结果def run_pipeline(self, prompt): Run the complete image generation and enhancement pipeline print(Starting image generation pipeline...) try: # Step 1: Generate initial image print(Generating initial image...) initial_image_path self.generate_initial_image(prompt) print(fInitial image saved to: {initial_image_path}) # Step 2: Evaluate image content print(Evaluating image content...) evaluation self.evaluate_image_content(initial_image_path, prompt) print(fEvaluation result: {evaluation}) if evaluation Content matches: print(Image content matches prompt perfectly.) return initial_image_path # Step 3: Analyze mismatched concepts print(Analyzing mismatched concepts...) concept_prompt self.analyze_mismatch_concepts(evaluation) print(fIdentified concepts: {concept_prompt}) # Step 4: Validate concepts concept_texts [t.strip() for t in concept_prompt.split()] valid_concepts self.validate_concepts(concept_texts) print(fValid concepts for retrieval: {valid_concepts}) if not valid_concepts: print(No valid concepts found for retrieval.) return initial_image_path # Step 5: Retrieve reference images print(Retrieving reference images...) reference_images self.retrieve_reference_images(valid_concepts) if not reference_images: print(No suitable reference images found.) return initial_image_path # Step 6: Generate enhanced image print(Generating enhanced image...) enhanced_image_path self.generate_enhanced_image( prompt, reference_images[0] ) print(fEnhanced image saved to: {enhanced_image_path}) return enhanced_image_path except Exception as e: print(fError in pipeline: {str(e)}) raise finally: # Ensure all models are cleaned up at the end self._cleanup_models()需要特别留意两个简化取舍来自源码注释与原始文档检索参考图像时只使用了第一个概念concepts[0]并且只返回最相似的一张图片top_image_paths[:1]受模型特性与单卡资源限制增强生成是“原始提示词 单张参考图”的图文联合生成如果想做多图提示联合生成原始文档建议可以尝试 Omnigen-V1 之类的方案自行扩展。入口处main.py的调用示例if __name__ __main__: # Example prompts prompts [ A beautiful retriever and a cradle., A car ] pipeline ImageRAGPipeline() for prompt in prompts: print(f\nProcessing prompt: {prompt}) try: final_image pipeline.run_pipeline(prompt) print(fFinal image for this prompt: {final_image}) except Exception as e: print(fFailed to process prompt {prompt}: {str(e)})7.3 流程效果演示以提示词A beautiful retriever and a cradle.为例仓库中保留了完整的中间结果模板图位于 datasets/templates提示词A beautiful retriever and a cradle.SDXL 直接生成的初始图像retriever 缺失/错位模型“幻觉”掉了摇椅元素VLM 找出的差异概念A cradle An ideaLLM 验证后的有效差异概念A cradle“An idea” 无法用图像描述被过滤CLIP 从 datasets/imgs 检索成功cradle.jpg以 cradle.jpg 为参考图结合原始提示词重新生成的增强图像对比两张结果图可以看到增强后的图像中“cradle摇椅”这一初始图缺失的概念被成功补全这正是 IMGRAG 通过外部图像数据补充模型缺失视觉信息效果的直观体现。8. 总结与扩展方向本文沿着 TinyIMGRAG 的文档脉络完整走了一遍简化版 IMGRAG 的搭建过程SDXLGenerator 负责两种模式的图像生成IMGRAG/ImgGenerator.pyQwen2.5-VL 负责图像与提示的一致性评估IMGRAG/ImgEvaluator.pyQwen2.5-7B Int4 负责差异概念的改写与校验IMGRAG/RewritePrompt.pyCLIP 负责参考图检索IMGRAG/ImgRetrieval.py最终由ImageRAGPipeline以懒加载 try/finally清理的方式在单张 3090 上编排全流程main.py。这个实现刻意选择了轻量模型3B VLM、Int4 量化 7B LLM、ViT-B-32 CLIP以保证单卡可跑通但原始文档也给出了明确的进阶方向检索与生成侧当前只取第一个有效概念、只返回一张最相似图片可以扩展为多概念、多图参考的联合生成评估与改写侧若希望获得更好的差异判断与文本改写质量可以接入更强的多模态大模型 API 替代本地轻量模型语料库侧检索质量直接受 datasets/imgs 语料覆盖度影响扩充外部图像数据库是提升长尾概念补全能力的直接手段。相关文档与参考资料模块原始文档content/TinyIMGRAG/README.md依赖版本清单content/TinyIMGRAG/requirements.txt模型下载脚本content/TinyIMGRAG/download_model.pyImageRAG: Dynamic Image Retrieval for Reference-Guided Image GenerationIP-Adapter: Text Compatible Image Prompt Adapter for Text-to-Image Diffusion Models赞分享示例工程教程【免费下载链接】tiny-universe《大模型白盒子构建指南》一个全手搓的Tiny-Universe项目地址https://gitcode.com/datawhalechina/tiny-universe点击查看免费下载相关推荐GraphRAG终极指南100天掌握基于图的检索增强生成技术GraphRAG终极指南100天掌握基于图的检索增强生成技术 GraphRAG是一个革命性的基于图的检索增强生成 RAG 系统它能从非结构化文本中提取有意义人工智能RAG知识图谱数据工程大模型Semantic Router OpenAI RAG 集成实战基于 File Store 与 Vector Store 的检索增强生成Semantic Router OpenAI RAG 集成实战基于 File Store 与 Vector Store 的检索增强生成 Semantic Ro后端API网关模型推理服务AI Agentmistral.rs 网络搜索增强生成实战指南基于 OpenAI 兼容 web_search_options 的检索增强推理mistral.rs 网络搜索增强生成实战指南基于 OpenAI 兼容 web_search_options 的检索增强推理 导读 本指南围绕 mistral推理引擎模型推理服务AI Agent多模态上一篇Conductor HITL 审批工作流实战让模型起草、让人类裁决、让送达恰好一次下一篇Marlin 风扇 PWM 转速不稳、不转SKR ProSTM32F407VE主板的完整排查指南创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考