[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-taesungp--contrastive-unpaired-translation":3,"tool-taesungp--contrastive-unpaired-translation":64},[4,17,27,35,43,56],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":16},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,3,"2026-04-05T11:01:52",[13,14,15],"开发框架","图像","Agent","ready",{"id":18,"name":19,"github_repo":20,"description_zh":21,"stars":22,"difficulty_score":23,"last_commit_at":24,"category_tags":25,"status":16},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",140436,2,"2026-04-05T23:32:43",[13,15,26],"语言模型",{"id":28,"name":29,"github_repo":30,"description_zh":31,"stars":32,"difficulty_score":23,"last_commit_at":33,"category_tags":34,"status":16},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",107662,"2026-04-03T11:11:01",[13,14,15],{"id":36,"name":37,"github_repo":38,"description_zh":39,"stars":40,"difficulty_score":23,"last_commit_at":41,"category_tags":42,"status":16},3704,"NextChat","ChatGPTNextWeb\u002FNextChat","NextChat 是一款轻量且极速的 AI 助手，旨在为用户提供流畅、跨平台的大模型交互体验。它完美解决了用户在多设备间切换时难以保持对话连续性，以及面对众多 AI 模型不知如何统一管理的痛点。无论是日常办公、学习辅助还是创意激发，NextChat 都能让用户随时随地通过网页、iOS、Android、Windows、MacOS 或 Linux 端无缝接入智能服务。\n\n这款工具非常适合普通用户、学生、职场人士以及需要私有化部署的企业团队使用。对于开发者而言，它也提供了便捷的自托管方案，支持一键部署到 Vercel 或 Zeabur 等平台。\n\nNextChat 的核心亮点在于其广泛的模型兼容性，原生支持 Claude、DeepSeek、GPT-4 及 Gemini Pro 等主流大模型，让用户在一个界面即可自由切换不同 AI 能力。此外，它还率先支持 MCP（Model Context Protocol）协议，增强了上下文处理能力。针对企业用户，NextChat 提供专业版解决方案，具备品牌定制、细粒度权限控制、内部知识库整合及安全审计等功能，满足公司对数据隐私和个性化管理的高标准要求。",87618,"2026-04-05T07:20:52",[13,26],{"id":44,"name":45,"github_repo":46,"description_zh":47,"stars":48,"difficulty_score":23,"last_commit_at":49,"category_tags":50,"status":16},2268,"ML-For-Beginners","microsoft\u002FML-For-Beginners","ML-For-Beginners 是由微软推出的一套系统化机器学习入门课程，旨在帮助零基础用户轻松掌握经典机器学习知识。这套课程将学习路径规划为 12 周，包含 26 节精炼课程和 52 道配套测验，内容涵盖从基础概念到实际应用的完整流程，有效解决了初学者面对庞大知识体系时无从下手、缺乏结构化指导的痛点。\n\n无论是希望转型的开发者、需要补充算法背景的研究人员，还是对人工智能充满好奇的普通爱好者，都能从中受益。课程不仅提供了清晰的理论讲解，还强调动手实践，让用户在循序渐进中建立扎实的技能基础。其独特的亮点在于强大的多语言支持，通过自动化机制提供了包括简体中文在内的 50 多种语言版本，极大地降低了全球不同背景用户的学习门槛。此外，项目采用开源协作模式，社区活跃且内容持续更新，确保学习者能获取前沿且准确的技术资讯。如果你正寻找一条清晰、友好且专业的机器学习入门之路，ML-For-Beginners 将是理想的起点。",84991,"2026-04-05T10:45:23",[14,51,52,53,15,54,26,13,55],"数据工具","视频","插件","其他","音频",{"id":57,"name":58,"github_repo":59,"description_zh":60,"stars":61,"difficulty_score":10,"last_commit_at":62,"category_tags":63,"status":16},3128,"ragflow","infiniflow\u002Fragflow","RAGFlow 是一款领先的开源检索增强生成（RAG）引擎，旨在为大语言模型构建更精准、可靠的上下文层。它巧妙地将前沿的 RAG 技术与智能体（Agent）能力相结合，不仅支持从各类文档中高效提取知识，还能让模型基于这些知识进行逻辑推理和任务执行。\n\n在大模型应用中，幻觉问题和知识滞后是常见痛点。RAGFlow 通过深度解析复杂文档结构（如表格、图表及混合排版），显著提升了信息检索的准确度，从而有效减少模型“胡编乱造”的现象，确保回答既有据可依又具备时效性。其内置的智能体机制更进一步，使系统不仅能回答问题，还能自主规划步骤解决复杂问题。\n\n这款工具特别适合开发者、企业技术团队以及 AI 研究人员使用。无论是希望快速搭建私有知识库问答系统，还是致力于探索大模型在垂直领域落地的创新者，都能从中受益。RAGFlow 提供了可视化的工作流编排界面和灵活的 API 接口，既降低了非算法背景用户的上手门槛，也满足了专业开发者对系统深度定制的需求。作为基于 Apache 2.0 协议开源的项目，它正成为连接通用大模型与行业专有知识之间的重要桥梁。",77062,"2026-04-04T04:44:48",[15,14,13,26,54],{"id":65,"github_repo":66,"name":67,"description_en":68,"description_zh":69,"ai_summary_zh":69,"readme_en":70,"readme_zh":71,"quickstart_zh":72,"use_case_zh":73,"hero_image_url":74,"owner_login":75,"owner_name":76,"owner_avatar_url":77,"owner_bio":78,"owner_company":79,"owner_location":79,"owner_email":79,"owner_twitter":79,"owner_website":79,"owner_url":80,"languages":81,"stars":94,"forks":95,"last_commit_at":96,"license":97,"difficulty_score":10,"env_os":98,"env_gpu":99,"env_ram":100,"env_deps":101,"category_tags":110,"github_topics":111,"view_count":23,"oss_zip_url":79,"oss_zip_packed_at":79,"status":16,"created_at":122,"updated_at":123,"faqs":124,"releases":155},2627,"taesungp\u002Fcontrastive-unpaired-translation","contrastive-unpaired-translation","Contrastive unpaired image-to-image translation, faster and lighter training than cyclegan (ECCV 2020, in PyTorch)","contrastive-unpaired-translation（简称 CUT）是一个基于 PyTorch 开发的开源项目，专注于解决无配对图像到图像的转换难题。它能够将一种风格的图片（如白天的街道）自动转换为另一种风格（如夜晚的街道），而无需提供成对的训练数据。\n\n相比经典的 CycleGAN，CUT 通过引入基于补丁的对比学习（PatchNCE）和对抗学习机制，成功摆脱了对复杂手工设计损失函数或逆向网络的依赖。这一创新不仅显著提升了训练速度，还大幅降低了显存占用，使得在普通硬件上高效训练成为可能。此外，该项目还支持极具特色的“单图像训练”模式，即仅用一张目标风格图片即可进行模型训练，极大地拓展了应用场景。\n\ncontrastive-unpaired-translation 非常适合计算机视觉领域的研究人员、AI 开发者以及需要快速验证想法的算法工程师使用。对于希望探索最新生成式模型技术或需要在资源受限环境下进行风格迁移实验的用户来说，这是一个轻量且高效的理想选择。项目代码结构清晰，并提供了详细的伪代码解释和预训练示例，便于用户快速上手与二次开发。","\n\n# Contrastive Unpaired Translation (CUT)\n\n### [video (1m)](https:\u002F\u002Fyoutu.be\u002FLlg0vE_MVgk) |  [video (10m)](https:\u002F\u002Fyoutu.be\u002FjSGOzjmN8q0) | [website](http:\u002F\u002Ftaesung.me\u002FContrastiveUnpairedTranslation\u002F) |   [paper](https:\u002F\u002Farxiv.org\u002Fpdf\u002F2007.15651)\n\u003Cbr>\n\n\u003Cimg src='https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaesungp_contrastive-unpaired-translation_readme_a8a762776913.gif' align=\"right\" width=960>\n\n\u003Cbr>\u003Cbr>\u003Cbr>\n\n\n\nWe provide our PyTorch implementation of unpaired image-to-image translation based on patchwise contrastive learning and adversarial learning.  No hand-crafted loss and inverse network is used. Compared to [CycleGAN](https:\u002F\u002Fgithub.com\u002Fjunyanz\u002FCycleGAN), our model training is faster and less memory-intensive. In addition, our method can be extended to single image training, where each “domain” is only a *single* image.\n\n\n\n\n[Contrastive Learning for Unpaired Image-to-Image Translation](http:\u002F\u002Ftaesung.me\u002FContrastiveUnpairedTranslation\u002F)  \n [Taesung Park](https:\u002F\u002Ftaesung.me\u002F), [Alexei A. Efros](https:\u002F\u002Fpeople.eecs.berkeley.edu\u002F~efros\u002F), [Richard Zhang](https:\u002F\u002Frichzhang.github.io\u002F), [Jun-Yan Zhu](https:\u002F\u002Fwww.cs.cmu.edu\u002F~junyanz\u002F)\u003Cbr>\nUC Berkeley and Adobe Research\u003Cbr>\n In ECCV 2020\n\n\n\u003Cimg src='https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaesungp_contrastive-unpaired-translation_readme_6c5117dc9ba6.gif' align=\"right\" width=960>\n\n\u003Cbr>\u003Cbr>\u003Cbr>\n\n### Pseudo code\n```python\nimport torch\ncross_entropy_loss = torch.nn.CrossEntropyLoss()\n\n# Input: f_q (BxCxS) and sampled features from H(G_enc(x))\n# Input: f_k (BxCxS) are sampled features from H(G_enc(G(x))\n# Input: tau is the temperature used in PatchNCE loss.\n# Output: PatchNCE loss\ndef PatchNCELoss(f_q, f_k, tau=0.07):\n    # batch size, channel size, and number of sample locations\n    B, C, S = f_q.shape\n\n    # calculate v * v+: BxSx1\n    l_pos = (f_k * f_q).sum(dim=1)[:, :, None]\n\n    # calculate v * v-: BxSxS\n    l_neg = torch.bmm(f_q.transpose(1, 2), f_k)\n\n    # The diagonal entries are not negatives. Remove them.\n    identity_matrix = torch.eye(S)[None, :, :]\n    l_neg.masked_fill_(identity_matrix, -float('inf'))\n\n    # calculate logits: (B)x(S)x(S+1)\n    logits = torch.cat((l_pos, l_neg), dim=2) \u002F tau\n\n    # return PatchNCE loss\n    predictions = logits.flatten(0, 1)\n    targets = torch.zeros(B * S, dtype=torch.long)\n    return cross_entropy_loss(predictions, targets)\n```\n## Example Results\n\n### Unpaired Image-to-Image Translation\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaesungp_contrastive-unpaired-translation_readme_6f64a86230f8.gif\" width=\"800px\"\u002F>\n\n### Single Image Unpaired Translation\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaesungp_contrastive-unpaired-translation_readme_77b875266459.gif\" width=\"800px\"\u002F>\n\n\n### Russian Blue Cat to Grumpy Cat\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaesungp_contrastive-unpaired-translation_readme_c305405164aa.jpg\" width=\"800px\"\u002F>\n\n### Parisian Street to Burano's painted houses\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaesungp_contrastive-unpaired-translation_readme_29b805e13858.jpg\" width=\"800px\"\u002F>\n\n\n\n## Prerequisites\n- Linux or macOS\n- Python 3\n- CPU or NVIDIA GPU + CUDA CuDNN\n\n### Update log\n\n9\u002F12\u002F2020: Added single-image translation.\n\n### Getting started\n\n- Clone this repo:\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Ftaesungp\u002Fcontrastive-unpaired-translation CUT\ncd CUT\n```\n\n- Install PyTorch 1.1 and other dependencies (e.g., torchvision, visdom, dominate, gputil).\n\n  For pip users, please type the command `pip install -r requirements.txt`.\n\n  For Conda users,  you can create a new Conda environment using `conda env create -f environment.yml`.\n\n\n### CUT and FastCUT Training and Test\n\n- Download the `grumpifycat` dataset (Fig 8 of the paper. Russian Blue -> Grumpy Cats)\n```bash\nbash .\u002Fdatasets\u002Fdownload_cut_dataset.sh grumpifycat\n```\nThe dataset is downloaded and unzipped at `.\u002Fdatasets\u002Fgrumpifycat\u002F`.\n\n- To view training results and loss plots, run `python -m visdom.server` and click the URL http:\u002F\u002Flocalhost:8097.\n\n- Train the CUT model:\n```bash\npython train.py --dataroot .\u002Fdatasets\u002Fgrumpifycat --name grumpycat_CUT --CUT_mode CUT\n```\n Or train the FastCUT model\n ```bash\npython train.py --dataroot .\u002Fdatasets\u002Fgrumpifycat --name grumpycat_FastCUT --CUT_mode FastCUT\n```\nThe checkpoints will be stored at `.\u002Fcheckpoints\u002Fgrumpycat_*\u002Fweb`.\n\n- Test the CUT model:\n```bash\npython test.py --dataroot .\u002Fdatasets\u002Fgrumpifycat --name grumpycat_CUT --CUT_mode CUT --phase train\n```\n\nThe test results will be saved to a html file here: `.\u002Fresults\u002Fgrumpifycat\u002Flatest_train\u002Findex.html`.\n\n### CUT, FastCUT, and CycleGAN\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaesungp_contrastive-unpaired-translation_readme_2f7c4c6e2a84.jpg\" width=\"800px\"\u002F>\u003Cbr>\n\nCUT is trained with the identity preservation loss and with `lambda_NCE=1`, while FastCUT is trained without the identity loss but with higher `lambda_NCE=10.0`. Compared to CycleGAN, CUT learns to perform more powerful distribution matching, while FastCUT is designed as a lighter (half the GPU memory, can fit a larger image), and faster (twice faster to train) alternative to CycleGAN. Please refer to the [paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F2007.15651) for more details.\n\nIn the above figure, we measure the percentage of pixels belonging to the horse\u002Fzebra bodies, using a pre-trained semantic segmentation model. We find a distribution mismatch between sizes of horses and zebras images -- zebras usually appear larger (36.8\\% vs. 17.9\\%). Our full method CUT has the flexibility to enlarge the horses, as a means of better matching of the training statistics than CycleGAN. FastCUT behaves more conservatively like CycleGAN.\n\n### Training using our launcher scripts\n\nPlease see `experiments\u002Fgrumpifycat_launcher.py` that generates the above command line arguments. The launcher scripts are useful for configuring rather complicated command-line arguments of training and testing.\n\nUsing the launcher, the command below generates the training command of CUT and FastCUT.\n```bash\npython -m experiments grumpifycat train 0   # CUT\npython -m experiments grumpifycat train 1   # FastCUT\n```\n\nTo test using the launcher,\n```bash\npython -m experiments grumpifycat test 0   # CUT\npython -m experiments grumpifycat test 1   # FastCUT\n```\n\nPossible commands are run, run_test, launch, close, and so on. Please see `experiments\u002F__main__.py` for all commands. Launcher is easy and quick to define and use. For example, the grumpifycat launcher is defined in a few lines:\n```python\nfrom .tmux_launcher import Options, TmuxLauncher\n\n\nclass Launcher(TmuxLauncher):\n    def common_options(self):\n        return [\n            Options(    # Command 0\n                dataroot=\".\u002Fdatasets\u002Fgrumpifycat\",\n                name=\"grumpifycat_CUT\",\n                CUT_mode=\"CUT\"\n            ),\n\n            Options(    # Command 1\n                dataroot=\".\u002Fdatasets\u002Fgrumpifycat\",\n                name=\"grumpifycat_FastCUT\",\n                CUT_mode=\"FastCUT\",\n            )\n        ]\n\n    def commands(self):\n        return [\"python train.py \" + str(opt) for opt in self.common_options()]\n\n    def test_commands(self):\n        # Russian Blue -> Grumpy Cats dataset does not have test split.\n        # Therefore, let's set the test split to be the \"train\" set.\n        return [\"python test.py \" + str(opt.set(phase='train')) for opt in self.common_options()]\n\n```\n\n\n\n### Apply a pre-trained CUT model and evaluate FID\n\nTo run the pretrained models, run the following.\n\n```bash\n\n# Download and unzip the pretrained models. The weights should be located at\n# checkpoints\u002Fhorse2zebra_cut_pretrained\u002Flatest_net_G.pth, for example.\nwget http:\u002F\u002Fefrosgans.eecs.berkeley.edu\u002FCUT\u002Fpretrained_models.tar\ntar -xf pretrained_models.tar\n\n# Generate outputs. The dataset paths might need to be adjusted.\n# To do this, modify the lines of experiments\u002Fpretrained_launcher.py\n# [id] corresponds to the respective commands defined in pretrained_launcher.py\n# 0 - CUT on Cityscapes\n# 1 - FastCUT on Cityscapes\n# 2 - CUT on Horse2Zebra\n# 3 - FastCUT on Horse2Zebra\n# 4 - CUT on Cat2Dog\n# 5 - FastCUT on Cat2Dog\npython -m experiments pretrained run_test [id]\n\n# Evaluate FID. To do this, first install pytorch-fid of https:\u002F\u002Fgithub.com\u002Fmseitzer\u002Fpytorch-fid\n# pip install pytorch-fid\n# For example, to evaluate horse2zebra FID of CUT,\n# python -m pytorch_fid .\u002Fdatasets\u002Fhorse2zebra\u002FtestB\u002F results\u002Fhorse2zebra_cut_pretrained\u002Ftest_latest\u002Fimages\u002Ffake_B\u002F\n# To evaluate Cityscapes FID of FastCUT,\n# python -m pytorch_fid .\u002Fdatasets\u002Fcityscapes\u002FvalA\u002F ~\u002Fprojects\u002Fcontrastive-unpaired-translation\u002Fresults\u002Fcityscapes_fastcut_pretrained\u002Ftest_latest\u002Fimages\u002Ffake_B\u002F\n# Note that a special dataset needs to be used for the Cityscapes model. Please read below. \npython -m pytorch_fid [path to real test images] [path to generated images]\n\n```\n\nNote: the Cityscapes pretrained model was trained and evaluated on a resized and JPEG-compressed version of the original Cityscapes dataset. To perform evaluation, please download [this](http:\u002F\u002Fefrosgans.eecs.berkeley.edu\u002FCUT\u002Fdatasets\u002Fcityscapes_val_for_CUT.tar) validation set and perform evaluation. \n\n\n### SinCUT Single Image Unpaired Training\n\nTo train SinCUT (single-image translation, shown in Fig 9, 13 and 14 of the paper), you need to\n\n1. set the `--model` option as `--model sincut`, which invokes the configuration and codes at `.\u002Fmodels\u002Fsincut_model.py`, and\n2. specify the dataset directory of one image in each domain, such as the example dataset included in this repo at `.\u002Fdatasets\u002Fsingle_image_monet_etretat\u002F`. \n\nFor example, to train a model for the [Etretat cliff (first image of Figure 13)](https:\u002F\u002Fgithub.com\u002Ftaesungp\u002Fcontrastive-unpaired-translation\u002Fblob\u002Fmaster\u002Fhttps:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaesungp_contrastive-unpaired-translation_readme_77b875266459.gif), please use the following command.\n\n```bash\npython train.py --model sincut --name singleimage_monet_etretat --dataroot .\u002Fdatasets\u002Fsingle_image_monet_etretat\n```\n\nor by using the experiment launcher script,\n```bash\npython -m experiments singleimage run 0\n```\n\nFor single-image translation, we adopt network architectural components of [StyleGAN2](https:\u002F\u002Fgithub.com\u002FNVlabs\u002Fstylegan2), as well as the pixel identity preservation loss used in [DTN](https:\u002F\u002Farxiv.org\u002Fabs\u002F1611.02200) and [CycleGAN](https:\u002F\u002Fgithub.com\u002Fjunyanz\u002Fpytorch-CycleGAN-and-pix2pix\u002Fblob\u002Fmaster\u002Fmodels\u002Fcycle_gan_model.py#L160). In particular, we adopted the code of [rosinality](https:\u002F\u002Fgithub.com\u002Frosinality\u002Fstylegan2-pytorch), which exists at `models\u002Fstylegan_networks.py`.\n\nThe training takes several hours. To generate the final image using the checkpoint,\n\n```bash\npython test.py --model sincut --name singleimage_monet_etretat --dataroot .\u002Fdatasets\u002Fsingle_image_monet_etretat\n```\n\nor simply\n\n```bash\npython -m experiments singleimage run_test 0\n```\n\n### [Datasets](.\u002Fdocs\u002Fdatasets.md)\nDownload CUT\u002FCycleGAN\u002Fpix2pix datasets. For example,\n\n```bash\nbash datasets\u002Fdownload_cut_datasets.sh horse2zebra\n```\n\nThe Cat2Dog dataset is prepared from the AFHQ dataset. Please visit https:\u002F\u002Fgithub.com\u002Fclovaai\u002Fstargan-v2 and download the AFHQ dataset by `bash download.sh afhq-dataset` of the github repo. Then reorganize directories as follows.\n```bash\nmkdir datasets\u002Fcat2dog\nln -s datasets\u002Fcat2dog\u002FtrainA [path_to_afhq]\u002Ftrain\u002Fcat\nln -s datasets\u002Fcat2dog\u002FtrainB [path_to_afhq]\u002Ftrain\u002Fdog\nln -s datasets\u002Fcat2dog\u002FtestA [path_to_afhq]\u002Ftest\u002Fcat\nln -s datasets\u002Fcat2dog\u002FtestB [path_to_afhq]\u002Ftest\u002Fdog\n```\n\nThe Cityscapes dataset can be downloaded from https:\u002F\u002Fcityscapes-dataset.com.\nAfter that, use the script `.\u002Fdatasets\u002Fprepare_cityscapes_dataset.py` to prepare the dataset. \n\n\n#### Preprocessing of input images\n\nThe preprocessing of the input images, such as resizing or random cropping, is controlled by the option `--preprocess`, `--load_size`, and `--crop_size`. The usage follows the [CycleGAN\u002Fpix2pix](https:\u002F\u002Fgithub.com\u002Fjunyanz\u002Fpytorch-CycleGAN-and-pix2pix) repo. \n\nFor example, the default setting `--preprocess resize_and_crop --load_size 286 --crop_size 256` resizes the input image to `286x286`, and then makes a random crop of size `256x256` as a way to perform data augmentation. There are other preprocessing options that can be specified, and they are specified in [base_dataset.py](https:\u002F\u002Fgithub.com\u002Ftaesungp\u002Fcontrastive-unpaired-translation\u002Fblob\u002Fmaster\u002Fdata\u002Fbase_dataset.py#L82). Below are some example options. \n\n - `--preprocess none`: does not perform any preprocessing. Note that the image size is still scaled to be a closest multiple of 4, because the convolutional generator cannot maintain the same image size otherwise. \n - `--preprocess scale_width --load_size 768`: scales the width of the image to be of size 768.\n - `--preprocess scale_shortside_and_crop`: scales the image preserving aspect ratio so that the short side is `load_size`, and then performs random cropping of window size `crop_size`.\n\nMore preprocessing options can be added by modifying [`get_transform()`](https:\u002F\u002Fgithub.com\u002Ftaesungp\u002Fcontrastive-unpaired-translation\u002Fblob\u002Fmaster\u002Fdata\u002Fbase_dataset.py#L82) of `base_dataset.py`. \n\n\n### Citation\nIf you use this code for your research, please cite our [paper](https:\u002F\u002Farxiv.org\u002Fpdf\u002F2007.15651).\n```\n@inproceedings{park2020cut,\n  title={Contrastive Learning for Unpaired Image-to-Image Translation},\n  author={Taesung Park and Alexei A. Efros and Richard Zhang and Jun-Yan Zhu},\n  booktitle={European Conference on Computer Vision},\n  year={2020}\n}\n```\n\nIf you use the original [pix2pix](https:\u002F\u002Fphillipi.github.io\u002Fpix2pix\u002F) and [CycleGAN](https:\u002F\u002Fjunyanz.github.io\u002FCycleGAN\u002F) model included in this repo, please cite the following papers\n```\n@inproceedings{CycleGAN2017,\n  title={Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networks},\n  author={Zhu, Jun-Yan and Park, Taesung and Isola, Phillip and Efros, Alexei A},\n  booktitle={IEEE International Conference on Computer Vision (ICCV)},\n  year={2017}\n}\n\n\n@inproceedings{isola2017image,\n  title={Image-to-Image Translation with Conditional Adversarial Networks},\n  author={Isola, Phillip and Zhu, Jun-Yan and Zhou, Tinghui and Efros, Alexei A},\n  booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},\n  year={2017}\n}\n```\n\n\n### Acknowledgments\nWe thank Allan Jabri and Phillip Isola for helpful discussion and feedback. Our code is developed based on [pytorch-CycleGAN-and-pix2pix](https:\u002F\u002Fgithub.com\u002Fjunyanz\u002Fpytorch-CycleGAN-and-pix2pix). We also thank [pytorch-fid](https:\u002F\u002Fgithub.com\u002Fmseitzer\u002Fpytorch-fid) for FID computation,  [drn](https:\u002F\u002Fgithub.com\u002Ffyu\u002Fdrn) for mIoU computation, and [stylegan2-pytorch](https:\u002F\u002Fgithub.com\u002Frosinality\u002Fstylegan2-pytorch\u002F) for the PyTorch implementation of StyleGAN2 used in our single-image translation setting.\n","# 对比无配对图像翻译 (CUT)\n\n### [视频 (1分钟)](https:\u002F\u002Fyoutu.be\u002FLlg0vE_MVgk) |  [视频 (10分钟)](https:\u002F\u002Fyoutu.be\u002FjSGOzjmN8q0) | [网站](http:\u002F\u002Ftaesung.me\u002FContrastiveUnpairedTranslation\u002F) |   [论文](https:\u002F\u002Farxiv.org\u002Fpdf\u002F2007.15651)\n\u003Cbr>\n\n\u003Cimg src='https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaesungp_contrastive-unpaired-translation_readme_a8a762776913.gif' align=\"right\" width=960>\n\n\u003Cbr>\u003Cbr>\u003Cbr>\n\n\n\n我们提供基于局部对比学习和对抗学习的无配对图像到图像翻译的 PyTorch 实现。该方法未使用手工设计的损失函数或逆向网络。与 [CycleGAN](https:\u002F\u002Fgithub.com\u002Fjunyanz\u002FCycleGAN) 相比，我们的模型训练速度更快且内存占用更少。此外，我们的方法还可以扩展到单张图像训练，其中每个“域”仅由*一张*图像构成。\n\n\n\n\n[用于无配对图像到图像翻译的对比学习](http:\u002F\u002Ftaesung.me\u002FContrastiveUnpairedTranslation\u002F)  \n [Taesung Park](https:\u002F\u002Ftaesung.me\u002F)、[Alexei A. Efros](https:\u002F\u002Fpeople.eecs.berkeley.edu\u002F~efros\u002F)、[Richard Zhang](https:\u002F\u002Frichzhang.github.io\u002F)、[Jun-Yan Zhu](https:\u002F\u002Fwww.cs.cmu.edu\u002F~junyanz\u002F)\u003Cbr>\n加州大学伯克利分校和 Adobe Research\u003Cbr>\n 在 ECCV 2020 上发表\n\n\n\u003Cimg src='https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaesungp_contrastive-unpaired-translation_readme_6c5117dc9ba6.gif' align=\"right\" width=960>\n\n\u003Cbr>\u003Cbr>\u003Cbr>\n\n### 伪代码\n```python\nimport torch\ncross_entropy_loss = torch.nn.CrossEntropyLoss()\n\n# 输入：f_q (BxCxS) 和从 H(G_enc(x)) 中采样的特征\n# 输入：f_k (BxCxS) 是从 H(G_enc(G(x))) 中采样的特征\n# 输入：tau 是 PatchNCE 损失中使用的温度。\n# 输出：PatchNCE 损失\ndef PatchNCELoss(f_q, f_k, tau=0.07):\n    # 批量大小、通道大小和采样位置的数量\n    B, C, S = f_q.shape\n\n    # 计算 v * v+：BxSx1\n    l_pos = (f_k * f_q).sum(dim=1)[:, :, None]\n\n    # 计算 v * v-：BxSxS\n    l_neg = torch.bmm(f_q.transpose(1, 2), f_k)\n\n    # 对角线元素不是负样本，将其移除。\n    identity_matrix = torch.eye(S)[None, :, :]\n    l_neg.masked_fill_(identity_matrix, -float('inf'))\n\n    # 计算 logits：(B)x(S)x(S+1)\n    logits = torch.cat((l_pos, l_neg), dim=2) \u002F tau\n\n    # 返回 PatchNCE 损失\n    predictions = logits.flatten(0, 1)\n    targets = torch.zeros(B * S, dtype=torch.long)\n    return cross_entropy_loss(predictions, targets)\n```\n## 示例结果\n\n### 无配对图像到图像翻译\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaesungp_contrastive-unpaired-translation_readme_6f64a86230f8.gif\" width=\"800px\"\u002F>\n\n### 单张图像无配对翻译\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaesungp_contrastive-unpaired-translation_readme_77b875266459.gif\" width=\"800px\"\u002F>\n\n\n### 俄罗斯蓝猫到暴躁猫\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaesungp_contrastive-unpaired-translation_readme_c305405164aa.jpg\" width=\"800px\"\u002F>\n\n### 巴黎街头到布拉诺彩绘房屋\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaesungp_contrastive-unpaired-translation_readme_29b805e13858.jpg\" width=\"800px\"\u002F>\n\n\n\n## 先决条件\n- Linux 或 macOS\n- Python 3\n- CPU 或 NVIDIA GPU + CUDA CuDNN\n\n### 更新日志\n\n2020年9月12日：增加了单张图像翻译功能。\n\n### 开始使用\n\n- 克隆此仓库：\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Ftaesungp\u002Fcontrastive-unpaired-translation CUT\ncd CUT\n```\n\n- 安装 PyTorch 1.1 及其他依赖项（如 torchvision、visdom、dominate、gputil）。\n\n  对于 pip 用户，请输入命令 `pip install -r requirements.txt`。\n\n  对于 Conda 用户，可以使用 `conda env create -f environment.yml` 创建一个新的 Conda 环境。\n\n\n### CUT 和 FastCUT 的训练与测试\n\n- 下载 `grumpifycat` 数据集（论文图8，俄罗斯蓝猫→暴躁猫）\n```bash\nbash .\u002Fdatasets\u002Fdownload_cut_dataset.sh grumpifycat\n```\n数据集将被下载并解压到 `.\u002Fdatasets\u002Fgrumpifycat\u002F`。\n\n- 要查看训练结果和损失曲线，请运行 `python -m visdom.server` 并点击 URL http:\u002F\u002Flocalhost:8097。\n\n- 训练 CUT 模型：\n```bash\npython train.py --dataroot .\u002Fdatasets\u002Fgrumpifycat --name grumpycat_CUT --CUT_mode CUT\n```\n或者训练 FastCUT 模型\n```bash\npython train.py --dataroot .\u002Fdatasets\u002Fgrumpifycat --name grumpycat_FastCUT --CUT_mode FastCUT\n```\n检查点将存储在 `.\u002Fcheckpoints\u002Fgrumpycat_*\u002Fweb`。\n\n- 测试 CUT 模型：\n```bash\npython test.py --dataroot .\u002Fdatasets\u002Fgrumpifycat --name grumpycat_CUT --CUT_mode CUT --phase train\n```\n\n测试结果将保存为 HTML 文件，位于 `.\u002Fresults\u002Fgrumpifycat\u002Flatest_train\u002Findex.html`。\n\n### CUT、FastCUT 和 CycleGAN\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaesungp_contrastive-unpaired-translation_readme_2f7c4c6e2a84.jpg\" width=\"800px\"\u002F>\u003Cbr>\n\nCUT 使用身份保持损失并设置 `lambda_NCE=1` 进行训练，而 FastCUT 则不使用身份损失，但设置了更高的 `lambda_NCE=10.0`。与 CycleGAN 相比，CUT 学习进行更强大的分布匹配，而 FastCUT 则是一种更轻量级（GPU 内存占用仅为 CycleGAN 的一半，可处理更大尺寸的图像）、训练速度更快（是 CycleGAN 的两倍）的替代方案。更多细节请参阅 [论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F2007.15651)。\n\n在上图中，我们使用预先训练好的语义分割模型来测量属于马或斑马身体的像素比例。我们发现马和斑马图像的尺寸分布存在差异——斑马通常显得更大（36.8% vs. 17.9%）。我们的完整方法 CUT 具有放大马的能力，从而能够更好地匹配训练数据的统计特性，这比 CycleGAN 更为出色。而 FastCUT 的表现则更保守，类似于 CycleGAN。\n\n### 使用我们的启动脚本进行训练\n\n请参阅 `experiments\u002Fgrumpifycat_launcher.py`，它会生成上述命令行参数。这些启动脚本对于配置复杂度较高的训练和测试命令行参数非常有用。\n\n通过启动脚本，以下命令可以生成 CUT 和 FastCUT 的训练命令。\n```bash\npython -m experiments grumpifycat train 0   # CUT\npython -m experiments grumpifycat train 1   # FastCUT\n```\n\n要使用启动脚本进行测试，\n```bash\npython -m experiments grumpifycat test 0   # CUT\npython -m experiments grumpifycat test 1   # FastCUT\n```\n\n可用的命令包括 run、run_test、launch、close 等。所有命令请参阅 `experiments\u002F__main__.py`。启动脚本易于定义和使用。例如，grumpifycat 启动脚本仅用几行代码即可定义：\n```python\nfrom .tmux_launcher import Options、TmuxLauncher\n\n\nclass Launcher(TmuxLauncher):\n    def common_options(self):\n        return [\n            Options(    # 命令 0\n                dataroot=\".\u002Fdatasets\u002Fgrumpifycat\",\n                name=\"grumpifycat_CUT\",\n                CUT_mode=\"CUT\"\n            ),\n\n            Options(    # 命令 1\n                dataroot=\".\u002Fdatasets\u002Fgrumpifycat\",\n                name=\"grumpifycat_FastCUT\",\n                CUT_mode=\"FastCUT\",\n            )\n        ]\n\n    def commands(self):\n        return [\"python train.py \" + str(opt) for opt in self.common_options()]\n\n    def test_commands(self):\n        # 俄罗斯蓝猫→暴躁猫的数据集没有测试集划分。\n        # 因此，我们将测试集设为“训练集”。\n        return [\"python test.py \" + str(opt.set(phase='train')) for opt in self.common_options()]\n\n```\n\n\n\n### 应用预训练的 CUT 模型并评估 FID\n\n要运行预训练的模型，请执行以下操作。\n\n```bash\n\n# 下载并解压预训练的模型。权重应位于\n\n# 例如，检查点\u002Fhorse2zebra_cut_pretrained\u002Flatest_net_G.pth。\nwget http:\u002F\u002Fefrosgans.eecs.berkeley.edu\u002FCUT\u002Fpretrained_models.tar\ntar -xf pretrained_models.tar\n\n# 生成输出。数据集路径可能需要调整。\n# 要做到这一点，修改experiments\u002Fpretrained_launcher.py中的相应行。\n# [id] 对应于pretrained_launcher.py中定义的各个命令：\n# 0 - 在Cityscapes数据集上使用CUT\n# 1 - 在Cityscapes数据集上使用FastCUT\n# 2 - 在Horse2Zebra数据集上使用CUT\n# 3 - 在Horse2Zebra数据集上使用FastCUT\n# 4 - 在Cat2Dog数据集上使用CUT\n# 5 - 在Cat2Dog数据集上使用FastCUT\npython -m experiments pretrained run_test [id]\n\n# 评估FID。为此，首先安装https:\u002F\u002Fgithub.com\u002Fmseitzer\u002Fpytorch-fid上的pytorch-fid。\n# pip install pytorch-fid\n# 例如，要评估Horse2Zebra数据集上CUT模型的FID，\n# python -m pytorch_fid .\u002Fdatasets\u002Fhorse2zebra\u002FtestB\u002F results\u002Fhorse2zebra_cut_pretrained\u002Ftest_latest\u002Fimages\u002Ffake_B\u002F\n# 要评估Cityscapes数据集上FastCUT模型的FID，\n# python -m pytorch_fid .\u002Fdatasets\u002Fcityscapes\u002FvalA\u002F ~\u002Fprojects\u002Fcontrastive-unpaired-translation\u002Fresults\u002Fcityscapes_fastcut_pretrained\u002Ftest_latest\u002Fimages\u002Ffake_B\u002F\n# 注意，Cityscapes模型需要使用特殊的数据集。请参阅下文。\npython -m pytorch_fid [真实测试图像路径] [生成图像路径]\n\n```\n\n注意：Cityscapes预训练模型是在原始Cityscapes数据集的缩放和JPEG压缩版本上进行训练和评估的。要进行评估，请下载[此链接](http:\u002F\u002Fefrosgans.eecs.berkeley.edu\u002FCUT\u002Fdatasets\u002Fcityscapes_val_for_CUT.tar)中的验证集并进行评估。\n\n\n### SinCUT 单张图像非配对训练\n\n要训练SinCUT（单张图像翻译，如论文中的图9、13和14所示），您需要：\n\n1. 将`--model`选项设置为`--model sincut`，这将调用位于`.\u002Fmodels\u002Fsincut_model.py`中的配置和代码；以及\n2. 指定每个域中包含一张图像的数据集目录，例如本仓库中包含的示例数据集`.\u002Fdatasets\u002Fsingle_image_monet_etretat\u002F`。\n\n例如，要训练一个用于[埃特雷塔悬崖（图13的第一张图片）](https:\u002F\u002Fgithub.com\u002Ftaesungp\u002Fcontrastive-unpaired-translation\u002Fblob\u002Fmaster\u002Fhttps:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaesungp_contrastive-unpaired-translation_readme_77b875266459.gif)的模型，请使用以下命令。\n\n```bash\npython train.py --model sincut --name singleimage_monet_etretat --dataroot .\u002Fdatasets\u002Fsingle_image_monet_etretat\n```\n\n或者使用实验启动脚本：\n\n```bash\npython -m experiments singleimage run 0\n```\n\n对于单张图像翻译，我们采用了[StyleGAN2](https:\u002F\u002Fgithub.com\u002FNVlabs\u002Fstylegan2)的网络架构组件，以及在[DTN](https:\u002F\u002Farxiv.org\u002Fabs\u002F1611.02200)和[CycleGAN](https:\u002F\u002Fgithub.com\u002Fjunyanz\u002Fpytorch-CycleGAN-and-pix2pix\u002Fblob\u002Fmaster\u002Fmodels\u002Fcycle_gan_model.py#L160)中使用的像素身份保持损失。特别是，我们借鉴了[rosinality](https:\u002F\u002Fgithub.com\u002Frosinality\u002Fstylegan2-pytorch)的代码，该代码位于`models\u002Fstylegan_networks.py`中。\n\n训练过程需要几个小时。要使用检查点生成最终图像，\n\n```bash\npython test.py --model sincut --name singleimage_monet_etretat --dataroot .\u002Fdatasets\u002Fsingle_image_monet_etretat\n```\n\n或者简单地：\n\n```bash\npython -m experiments singleimage run_test 0\n```\n\n### [数据集](.\u002Fdocs\u002Fdatasets.md)\n下载CUT\u002FCycleGAN\u002Fpix2pix数据集。例如，\n\n```bash\nbash datasets\u002Fdownload_cut_datasets.sh horse2zebra\n```\n\nCat2Dog数据集是从AFHQ数据集准备的。请访问https:\u002F\u002Fgithub.com\u002Fclovaai\u002Fstargan-v2，通过该仓库的`bash download.sh afhq-dataset`下载AFHQ数据集。然后按如下方式重新组织目录：\n```bash\nmkdir datasets\u002Fcat2dog\nln -s datasets\u002Fcat2dog\u002FtrainA [path_to_afhq]\u002Ftrain\u002Fcat\nln -s datasets\u002Fcat2dog\u002FtrainB [path_to_afhq]\u002Ftrain\u002Fdog\nln -s datasets\u002Fcat2dog\u002FtestA [path_to_afhq]\u002Ftest\u002Fcat\nln -s datasets\u002Fcat2dog\u002FtestB [path_to_afhq]\u002Ftest\u002Fdog\n```\n\nCityscapes数据集可以从https:\u002F\u002Fcityscapes-dataset.com下载。之后，使用`.\u002Fdatasets\u002Fprepare_cityscapes_dataset.py`脚本来准备数据集。\n\n\n#### 输入图像的预处理\n\n输入图像的预处理，如调整大小或随机裁剪，由`--preprocess`、`--load_size`和`--crop_size`选项控制。其用法遵循[CycleGAN\u002Fpix2pix](https:\u002F\u002Fgithub.com\u002Fjunyanz\u002Fpytorch-CycleGAN-and-pix2pix)仓库中的做法。\n\n例如，默认设置`--preprocess resize_and_crop --load_size 286 --crop_size 256`会将输入图像调整为`286x286`大小，然后随机裁剪出`256x256`的区域，以此进行数据增强。还有其他可指定的预处理选项，这些选项在[base_dataset.py](https:\u002F\u002Fgithub.com\u002Ftaesungp\u002Fcontrastive-unpaired-translation\u002Fblob\u002Fmaster\u002Fdata\u002Fbase_dataset.py#L82)中定义。以下是一些示例选项：\n\n - `--preprocess none`：不进行任何预处理。请注意，图像尺寸仍会被缩放到最接近的4的倍数，因为卷积生成器无法在其他情况下保持相同的图像尺寸。\n - `--preprocess scale_width --load_size 768`：将图像宽度缩放到768。\n - `--preprocess scale_shortside_and_crop`：按比例缩放图像，使短边达到`load_size`大小，然后随机裁剪出`crop_size`大小的窗口。\n\n可以通过修改`base_dataset.py`中的[`get_transform()`](https:\u002F\u002Fgithub.com\u002Ftaesungp\u002Fcontrastive-unpaired-translation\u002Fblob\u002Fmaster\u002Fdata\u002Fbase_dataset.py#L82)来添加更多预处理选项。\n\n\n### 引用\n如果您在研究中使用此代码，请引用我们的[论文](https:\u002F\u002Farxiv.org\u002Fpdf\u002F2007.15651)。\n```\n@inproceedings{park2020cut,\n  title={Contrastive Learning for Unpaired Image-to-Image Translation},\n  author={Taesung Park and Alexei A. Efros and Richard Zhang and Jun-Yan Zhu},\n  booktitle={European Conference on Computer Vision},\n  year={2020}\n}\n```\n\n如果您使用本仓库中包含的原始[pix2pix](https:\u002F\u002Fphillipi.github.io\u002Fpix2pix\u002F)和[CycleGAN](https:\u002F\u002Fjunyanz.github.io\u002FCycleGAN\u002F)模型，请引用以下论文：\n```\n@inproceedings{CycleGAN2017,\n  title={Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networks},\n  author={Zhu, Jun-Yan and Park, Taesung and Isola, Phillip and Efros, Alexei A},\n  booktitle={IEEE International Conference on Computer Vision (ICCV)},\n  year={2017}\n}\n\n\n@inproceedings{isola2017image,\n  title={Image-to-Image Translation with Conditional Adversarial Networks},\n  author={Isola, Phillip and Zhu, Jun-Yan and Zhou, Tinghui and Efros, Alexei A},\n  booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},\n  year={2017}\n}\n```\n\n### 致谢\n我们感谢艾伦·贾布里和菲利普·伊索拉提供的有益讨论和反馈。我们的代码基于 [pytorch-CycleGAN-and-pix2pix](https:\u002F\u002Fgithub.com\u002Fjunyanz\u002Fpytorch-CycleGAN-and-pix2pix) 开发。同时，我们也感谢 [pytorch-fid](https:\u002F\u002Fgithub.com\u002Fmseitzer\u002Fpytorch-fid) 提供的 FID 计算功能、[drn](https:\u002F\u002Fgithub.com\u002Ffyu\u002Fdrn) 提供的 mIoU 计算功能，以及 [stylegan2-pytorch](https:\u002F\u002Fgithub.com\u002Frosinality\u002Fstylegan2-pytorch\u002F) 为我们单图像转换任务中使用的 StyleGAN2 的 PyTorch 实现所提供的支持。","# Contrastive Unpaired Translation (CUT) 快速上手指南\n\nCUT 是一个基于对比学习的非配对图像到图像翻译工具。相比 CycleGAN，它具有训练更快、显存占用更低的特点，并支持单张图像训练模式（SinCUT）。\n\n## 环境准备\n\n*   **操作系统**: Linux 或 macOS\n*   **Python**: Python 3\n*   **硬件**: CPU 或 NVIDIA GPU (需安装 CUDA 和 CuDNN)\n*   **深度学习框架**: PyTorch 1.1+\n\n> **国内加速建议**：\n> 在安装依赖时，推荐使用清华或阿里镜像源以加快下载速度。\n> *   pip: `pip install -r requirements.txt -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple`\n> *   conda: 配置 `.condarc` 使用清华源 (`https:\u002F\u002Fmirrors.tuna.tsinghua.edu.cn\u002Fanaconda\u002Fpkgs\u002Fmain\u002F`)\n\n## 安装步骤\n\n1.  **克隆仓库**\n    ```bash\n    git clone https:\u002F\u002Fgithub.com\u002Ftaesungp\u002Fcontrastive-unpaired-translation CUT\n    cd CUT\n    ```\n\n2.  **安装依赖**\n    选择以下任一方式安装所需库（如 torchvision, visdom, dominate 等）：\n\n    *   **使用 pip**:\n        ```bash\n        pip install -r requirements.txt\n        # 国内用户推荐：\n        # pip install -r requirements.txt -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple\n        ```\n\n    *   **使用 Conda**:\n        ```bash\n        conda env create -f environment.yml\n        conda activate cut\n        ```\n\n## 基本使用\n\n以下以官方提供的 \"grumpifycat\" (蓝猫变不爽猫) 数据集为例，演示从数据下载到训练、测试的全流程。\n\n### 1. 下载示例数据集\n```bash\nbash .\u002Fdatasets\u002Fdownload_cut_dataset.sh grumpifycat\n```\n数据将解压至 `.\u002Fdatasets\u002Fgrumpifycat\u002F` 目录。\n\n### 2. 启动可视化监控 (可选)\n在终端运行以下命令，然后在浏览器访问 `http:\u002F\u002Flocalhost:8097` 查看训练损失和结果图。\n```bash\npython -m visdom.server\n```\n\n### 3. 训练模型\n你可以选择训练标准 **CUT** 模型或更轻量的 **FastCUT** 模型。\n\n*   **训练 CUT 模型**:\n    ```bash\n    python train.py --dataroot .\u002Fdatasets\u002Fgrumpifycat --name grumpycat_CUT --CUT_mode CUT\n    ```\n\n*   **训练 FastCUT 模型** (速度更快，显存占用减半):\n    ```bash\n    python train.py --dataroot .\u002Fdatasets\u002Fgrumpifycat --name grumpycat_FastCUT --CUT_mode FastCUT\n    ```\n    *检查点将保存在 `.\u002Fcheckpoints\u002Fgrumpycat_*\u002Fweb`。*\n\n### 4. 测试与生成结果\n使用训练好的模型生成转换后的图像。\n\n```bash\npython test.py --dataroot .\u002Fdatasets\u002Fgrumpifycat --name grumpycat_CUT --CUT_mode CUT --phase train\n```\n*注意：由于该示例数据集没有独立的测试集，因此 `--phase` 设置为 `train`。*\n\n生成的结果将保存为 HTML 文件，路径如下：\n`.\u002Fresults\u002Fgrumpifycat\u002Flatest_train\u002Findex.html`\n直接在浏览器打开该文件即可查看对比效果。\n\n---\n**进阶提示**：\n若需进行单张图像风格迁移（SinCUT），请使用 `--model sincut` 参数，并将数据根目录指向仅包含单张图片的文件夹。","一家独立游戏工作室的美术团队急需将大量手绘的“夏日森林”场景素材转换为“冬日雪景”，但团队并未收集成对的夏冬同位置图片，且服务器显存资源十分紧张。\n\n### 没有 contrastive-unpaired-translation 时\n- **数据准备困难**：由于缺乏严格对齐的“夏 - 冬”配对图片，传统监督学习方法无法直接应用，人工合成配对数据耗时耗力。\n- **训练成本高昂**：若采用 CycleGAN 等旧方案，模型训练速度缓慢且极度消耗显存，导致在单张消费级显卡上几乎无法跑通大分辨率图像训练。\n- **风格迁移失真**：现有无配对方法容易丢失原图的结构细节（如树木形态、道路走向），生成的雪景往往模糊不清或产生伪影，需后期大量修图。\n- **单图适配受限**：若只想针对某一张特定的概念图进行风格化尝试，旧模型难以在仅有一张参考图的情况下稳定工作。\n\n### 使用 contrastive-unpaired-translation 后\n- **无需配对数据**：利用其基于补丁对比学习（PatchNCE）的特性，直接输入未对齐的夏日图集和冬日图集即可开始训练，彻底免去人工配对环节。\n- **训练轻量高效**：得益于更轻量的架构设计，训练速度显著快于 CycleGAN 且显存占用更低，使团队能在普通 GPU 上快速迭代模型。\n- **结构保持精准**：通过对比损失函数强制保留输入图像的空间结构，生成的雪景不仅色调准确，还完美保留了原有的树木轮廓与地形细节。\n- **支持单图训练**：即使只有一张夏日草图，也能扩展为单图像训练模式，迅速生成对应的冬日版本，极大提升了概念设计的灵活性。\n\ncontrastive-unpaired-translation 通过引入对比学习机制，以更低的数据门槛和计算成本，实现了高保真度的无配对图像风格迁移。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaesungp_contrastive-unpaired-translation_77b87526.gif","taesungp","Taesung Park","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Ftaesungp_c2b0df39.jpg","https:\u002F\u002Ftaesung.me",null,"https:\u002F\u002Fgithub.com\u002Ftaesungp",[82,86,90],{"name":83,"color":84,"percentage":85},"Python","#3572A5",98.2,{"name":87,"color":88,"percentage":89},"Shell","#89e051",1,{"name":91,"color":92,"percentage":93},"TeX","#3D6117",0.8,2496,447,"2026-03-30T09:38:54","NOASSERTION","Linux, macOS","需要 NVIDIA GPU（用于加速训练），支持 CUDA 和 CuDNN；CPU 亦可运行但速度较慢。显存需求：FastCUT 模式比 CycleGAN 节省一半显存，具体大小取决于图像分辨率，未明确最低数值。","未说明",{"notes":102,"python":103,"dependencies":104},"该项目基于 PyTorch 1.1 版本（较旧），建议使用 Conda 创建环境并通过 environment.yml 安装依赖。支持单图像训练模式（SinCUT），此时会引入 StyleGAN2 的网络架构组件。Cityscapes 数据集的预训练模型需要在经过调整大小和 JPEG 压缩的特定验证集上进行评估。","3",[105,106,107,108,109],"torch==1.1","torchvision","visdom","dominate","gputil",[14,13],[112,113,114,115,116,117,118,119,120,121],"pytorch","computervision","deeplearning","cyclegan","image-generation","computer-vision","computer-graphics","image-manipulation","gans","generative-adversarial-network","2026-03-27T02:49:30.150509","2026-04-06T08:47:29.074800",[125,130,135,140,145,150],{"id":126,"question_zh":127,"answer_zh":128,"source_url":129},12144,"如何在自定义数据集上测试预训练模型？需要如何组织数据文件夹？","虽然官方文档建议创建 testA 和 testB 文件夹，但对于单组图像的测试，核心在于理解 GAN 网络的基本评估流程。对于具体的 CUT、FastCUT、CycleGAN 等模型，建议参考相关的深度学习讲座（如 DeepMind 的 GAN 教程）来理解其原理。在实际操作中，通常需要将自定义数据集按照项目文档（docs\u002Fdataset.md）的要求进行组织，如果是非配对数据，可能需要使用 `datasets\u002Fcombine_A_and_B.py` 脚本将两个域的数据合并处理。","https:\u002F\u002Fgithub.com\u002Ftaesungp\u002Fcontrastive-unpaired-translation\u002Fissues\u002F87",{"id":131,"question_zh":132,"answer_zh":133,"source_url":134},12145,"遇到 'RuntimeError: merge_sort: failed to synchronize: cudaErrorIllegalAddress' 错误如何解决？","这是一个在 PyTorch 1.8 + CUDA 11 环境下已知的兼容性问题，即使 CycleGAN 能正常运行，CUT 模型也可能触发此错误。解决方案是修改源代码 `models\u002Fnetworks.py` 第 565 行附近的代码。将原本使用 `torch.randperm` 生成随机排列的代码：\n`patch_id = torch.randperm(feat_reshape.shape[1], device=feats[0].device)`\n替换为 numpy 的实现：\n`patch_id = np.random.permutation(feat_reshape.shape[1])`\n注意：如果替换后涉及设备转移问题，可能需要确保后续操作能正确处理 numpy 数组或将其转回 tensor。此方法已在多个用户环境中验证有效。","https:\u002F\u002Fgithub.com\u002Ftaesungp\u002Fcontrastive-unpaired-translation\u002Fissues\u002F83",{"id":136,"question_zh":137,"answer_zh":138,"source_url":139},12146,"复现 GTA 到 Cityscapes 的翻译效果时，应该使用什么样的超参数和数据集设置？","要获得良好的 GTA 到 Cityscapes 翻译效果，首先需要严格按照 `docs\u002Fdataset.md` 中的说明组织数据集。获取 GTA 和 Cityscapes 数据集后，使用以下命令将它们组合：\n`python datasets\u002Fcombine_A_and_B.py --fold_A \u002Fpath\u002Fto\u002Fdata\u002FA --fold_B \u002Fpath\u002Fto\u002Fdata\u002FB --fold_AB \u002Fpath\u002Fto\u002Fdata`\n关于超参数，作者提到在显存允许的情况下，曾尝试过 `load_size\u002Fcrop_size` 为 `1024\u002F384` 的设置。保持 `load_size` 不要比 `crop_size` 大太多（例如比例接近 1.1\u002F1 到 2\u002F1 之间）通常效果更好，因为这样能给生成器提供更多的上下文信息，避免裁剪图像过度放大。","https:\u002F\u002Fgithub.com\u002Ftaesungp\u002Fcontrastive-unpaired-translation\u002Fissues\u002F16",{"id":141,"question_zh":142,"answer_zh":143,"source_url":144},12147,"训练结果中输入图像显示为空白或输出图像颜色异常（全白\u002F全灰）是什么原因？","这通常是由输入图像的位深（bit-depth）或数值缩放问题引起的。常见原因包括：\n1. 数据集包含 16 位图像，而模型预期是 8 位图像，导致数值解析错误。\n2. 输入\u002F输出值的缩放比例不正确。如果真实图像（real_A）显示全白，意味着像素值饱和在 1.0；如果生成图像（fake_B）显示全灰，意味着所有值为 0。\n解决方法：检查数据集图像格式，确保转换为标准的 8 位图像。如果是代码层面的可视化问题，可以检查 `utils\u002Fvisualizer.py` 中关于图像归一化和乘以 255 的逻辑，确保输入数据在 [0, 1] 或 [0, 255] 的正确范围内。","https:\u002F\u002Fgithub.com\u002Ftaesungp\u002Fcontrastive-unpaired-translation\u002Fissues\u002F31",{"id":146,"question_zh":147,"answer_zh":148,"source_url":149},12148,"代码中 PatchNceLoss 的计算逻辑与论文伪代码不一致，是实现错误吗？","这不是错误，而是变量定义的上下文不同造成的误解。在 `nce.py` 代码中，变量 `batchSize` 实际上指的是“补丁（patches）的批量大小”，即论文伪代码中的 `B × S`（图像批大小 × 每个图像的补丁数），而不是图像的批大小 `B`。\n这种重塑（reshaping）操作发生在 `netF` 内部（见 `models\u002Fnetworks.py` 第 570 行）。因此，代码中的 `torch.bmm` 操作实际上是在计算 `(BS×1×C)` 和 `(BS×C×1)` 的矩阵乘法，最终得到 `BS×1` 的结果，这与伪代码逻辑是一致的。","https:\u002F\u002Fgithub.com\u002Ftaesungp\u002Fcontrastive-unpaired-translation\u002Fissues\u002F1",{"id":151,"question_zh":152,"answer_zh":153,"source_url":154},12149,"在微调（Finetuning）阶段，设置的 `load_size` 参数被忽略，只使用了 `crop_size`，这是正常的吗？","是的，这是预期行为。在微调阶段（通常是第 201-400 轮），为了稳定训练并防止过度拟合，代码会禁用部分数据增强（如随机缩放和裁剪），此时 `load_size` 会被忽略，直接以 `crop_size` 为准。虽然代码注释中曾暗示这只适用于 FastCUT，但实际上标准 CUT 模型在微调阶段也采用此策略。\n此外，作者建议 `load_size` 不应比 `crop_size` 大太多（推荐比例接近 1.1:1），因为在训练阶段较大的 `load_size` 能提供上下文，但在微调时固定尺寸更有助于收敛。","https:\u002F\u002Fgithub.com\u002Ftaesungp\u002Fcontrastive-unpaired-translation\u002Fissues\u002F139",[]]