[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-YuanGongND--ast":3,"tool-YuanGongND--ast":61},[4,18,26,36,44,53],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":17},4358,"openclaw","openclaw\u002Fopenclaw","OpenClaw 是一款专为个人打造的本地化 AI 助手，旨在让你在自己的设备上拥有完全可控的智能伙伴。它打破了传统 AI 助手局限于特定网页或应用的束缚，能够直接接入你日常使用的各类通讯渠道，包括微信、WhatsApp、Telegram、Discord、iMessage 等数十种平台。无论你在哪个聊天软件中发送消息，OpenClaw 都能即时响应，甚至支持在 macOS、iOS 和 Android 设备上进行语音交互，并提供实时的画布渲染功能供你操控。\n\n这款工具主要解决了用户对数据隐私、响应速度以及“始终在线”体验的需求。通过将 AI 部署在本地，用户无需依赖云端服务即可享受快速、私密的智能辅助，真正实现了“你的数据，你做主”。其独特的技术亮点在于强大的网关架构，将控制平面与核心助手分离，确保跨平台通信的流畅性与扩展性。\n\nOpenClaw 非常适合希望构建个性化工作流的技术爱好者、开发者，以及注重隐私保护且不愿被单一生态绑定的普通用户。只要具备基础的终端操作能力（支持 macOS、Linux 及 Windows WSL2），即可通过简单的命令行引导完成部署。如果你渴望拥有一个懂你",349277,3,"2026-04-06T06:32:30",[13,14,15,16],"Agent","开发框架","图像","数据工具","ready",{"id":19,"name":20,"github_repo":21,"description_zh":22,"stars":23,"difficulty_score":10,"last_commit_at":24,"category_tags":25,"status":17},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,"2026-04-05T11:01:52",[14,15,13],{"id":27,"name":28,"github_repo":29,"description_zh":30,"stars":31,"difficulty_score":32,"last_commit_at":33,"category_tags":34,"status":17},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 真正成长为懂上",149489,2,"2026-04-10T11:32:46",[14,13,35],"语言模型",{"id":37,"name":38,"github_repo":39,"description_zh":40,"stars":41,"difficulty_score":32,"last_commit_at":42,"category_tags":43,"status":17},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 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",108322,"2026-04-10T11:39:34",[14,15,13],{"id":45,"name":46,"github_repo":47,"description_zh":48,"stars":49,"difficulty_score":32,"last_commit_at":50,"category_tags":51,"status":17},6121,"gemini-cli","google-gemini\u002Fgemini-cli","gemini-cli 是一款由谷歌推出的开源 AI 命令行工具，它将强大的 Gemini 大模型能力直接集成到用户的终端环境中。对于习惯在命令行工作的开发者而言，它提供了一条从输入提示词到获取模型响应的最短路径，无需切换窗口即可享受智能辅助。\n\n这款工具主要解决了开发过程中频繁上下文切换的痛点，让用户能在熟悉的终端界面内直接完成代码理解、生成、调试以及自动化运维任务。无论是查询大型代码库、根据草图生成应用，还是执行复杂的 Git 操作，gemini-cli 都能通过自然语言指令高效处理。\n\n它特别适合广大软件工程师、DevOps 人员及技术研究人员使用。其核心亮点包括支持高达 100 万 token 的超长上下文窗口，具备出色的逻辑推理能力；内置 Google 搜索、文件操作及 Shell 命令执行等实用工具；更独特的是，它支持 MCP（模型上下文协议），允许用户灵活扩展自定义集成，连接如图像生成等外部能力。此外，个人谷歌账号即可享受免费的额度支持，且项目基于 Apache 2.0 协议完全开源，是提升终端工作效率的理想助手。",100752,"2026-04-10T01:20:03",[52,13,15,14],"插件",{"id":54,"name":55,"github_repo":56,"description_zh":57,"stars":58,"difficulty_score":32,"last_commit_at":59,"category_tags":60,"status":17},4721,"markitdown","microsoft\u002Fmarkitdown","MarkItDown 是一款由微软 AutoGen 团队打造的轻量级 Python 工具，专为将各类文件高效转换为 Markdown 格式而设计。它支持 PDF、Word、Excel、PPT、图片（含 OCR）、音频（含语音转录）、HTML 乃至 YouTube 链接等多种格式的解析，能够精准提取文档中的标题、列表、表格和链接等关键结构信息。\n\n在人工智能应用日益普及的今天，大语言模型（LLM）虽擅长处理文本，却难以直接读取复杂的二进制办公文档。MarkItDown 恰好解决了这一痛点，它将非结构化或半结构化的文件转化为模型“原生理解”且 Token 效率极高的 Markdown 格式，成为连接本地文件与 AI 分析 pipeline 的理想桥梁。此外，它还提供了 MCP（模型上下文协议）服务器，可无缝集成到 Claude Desktop 等 LLM 应用中。\n\n这款工具特别适合开发者、数据科学家及 AI 研究人员使用，尤其是那些需要构建文档检索增强生成（RAG）系统、进行批量文本分析或希望让 AI 助手直接“阅读”本地文件的用户。虽然生成的内容也具备一定可读性，但其核心优势在于为机器",93400,"2026-04-06T19:52:38",[52,14],{"id":62,"github_repo":63,"name":64,"description_en":65,"description_zh":66,"ai_summary_zh":67,"readme_en":68,"readme_zh":69,"quickstart_zh":70,"use_case_zh":71,"hero_image_url":72,"owner_login":73,"owner_name":74,"owner_avatar_url":75,"owner_bio":76,"owner_company":77,"owner_location":78,"owner_email":79,"owner_twitter":80,"owner_website":81,"owner_url":82,"languages":83,"stars":96,"forks":97,"last_commit_at":98,"license":99,"difficulty_score":32,"env_os":100,"env_gpu":101,"env_ram":102,"env_deps":103,"category_tags":115,"github_topics":117,"view_count":32,"oss_zip_url":80,"oss_zip_packed_at":80,"status":17,"created_at":126,"updated_at":127,"faqs":128,"releases":162},6322,"YuanGongND\u002Fast","ast","Code for the Interspeech 2021 paper \"AST: Audio Spectrogram Transformer\".","AST（Audio Spectrogram Transformer）是一款基于 PyTorch 开发的开源音频分类模型，源自 Interspeech 2021 的研究成果。它致力于解决传统音频处理依赖卷积神经网络（CNN）的局限，首创了完全摒弃卷积操作、纯粹基于注意力机制的架构。这一设计使 AST 能够直接处理可变长度的音频输入，在无需复杂预处理的情况下，于 AudioSet、ESC-50 及 Speech Commands V2 等多个权威基准测试中刷新了最高准确率记录。\n\nAST 的核心技术亮点在于其“无卷积”特性，通过直接将音频频谱图转化为序列数据进行建模，不仅简化了模型结构，还显著提升了对不同音频任务的泛化能力。项目提供了详尽的训练脚本和预训练模型，支持用户通过少量代码甚至一键式脚本快速复现顶尖效果，同时也包含了 Google Colab 演示以便直观体验。\n\n这款工具非常适合音频领域的研究人员、算法工程师及深度学习开发者使用。无论是希望探索 Transformer 在音频领域应用的研究者，还是需要高效基线模型进行二次开发的工程师，AST 都能提供强有力的支持。其清晰的代码结构","AST（Audio Spectrogram Transformer）是一款基于 PyTorch 开发的开源音频分类模型，源自 Interspeech 2021 的研究成果。它致力于解决传统音频处理依赖卷积神经网络（CNN）的局限，首创了完全摒弃卷积操作、纯粹基于注意力机制的架构。这一设计使 AST 能够直接处理可变长度的音频输入，在无需复杂预处理的情况下，于 AudioSet、ESC-50 及 Speech Commands V2 等多个权威基准测试中刷新了最高准确率记录。\n\nAST 的核心技术亮点在于其“无卷积”特性，通过直接将音频频谱图转化为序列数据进行建模，不仅简化了模型结构，还显著提升了对不同音频任务的泛化能力。项目提供了详尽的训练脚本和预训练模型，支持用户通过少量代码甚至一键式脚本快速复现顶尖效果，同时也包含了 Google Colab 演示以便直观体验。\n\n这款工具非常适合音频领域的研究人员、算法工程师及深度学习开发者使用。无论是希望探索 Transformer 在音频领域应用的研究者，还是需要高效基线模型进行二次开发的工程师，AST 都能提供强有力的支持。其清晰的代码结构和灵活的配置方式，也让它成为学习先进音频分类技术的理想范例。","\n# AST: Audio Spectrogram Transformer  \n - [News](#News)\n - [Introduction](#Introduction)\n - [Citing](#Citing)  \n - [Getting Started](#Getting-Started)\n - [ESC-50 Recipe](#ESC-50-Recipe)  \n - [Speechcommands Recipe](#Speechcommands-V2-Recipe)  \n - [AudioSet Recipe](#Audioset-Recipe)\n - [Pretrained Models](#Pretrained-Models)\n - [Use Pretrained Model For Downstream Tasks](#Use-Pretrained-Model-For-Downstream-Tasks)\n - [Contact](#Contact)\n\n## News\nMay, 2023: We have released demo for our audio large language model LTU (listen, think, and understand) that can do zero-shot audio classification and advanced reasoning. Try the online interactive demo **[[here]](https:\u002F\u002Fgithub.com\u002FYuanGongND\u002Fltu)**.\n\nNovember, 2022: We decoupe `dataset` and hyper-parameters by moving hyper-parameters from `src\u002Frun.py` and `src\u002Ftraintest.py` to `egs\u002F{audioset,esc50,speechcommands}\u002Frun.sh`, so that it is easier to adapt the scripts to new datasets. This might cause a bug, please report if you have any issue running any recipe.\n\nOctober, 2022: We add an one-click, self-contained Google Colab script for (pretrained) AST inference with attention visualization. Please test the model with your own audio at [![Open In Colab](https:\u002F\u002Fcolab.research.google.com\u002Fassets\u002Fcolab-badge.svg)](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FYuanGongND\u002Fast\u002Fblob\u002Fmaster\u002Fcolab\u002FAST_Inference_Demo.ipynb) by one click (no GPU needed). \n\nMay, 2022: It was found that newer `torchaudio` package has different behavior with older ones in SpecAugment and will cause a [bug](https:\u002F\u002Fgithub.com\u002FYuanGongND\u002Fast\u002Fissues\u002F58). We find a workaround and fixed it. If you are interested, see [here](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FYuanGongND\u002Fast\u002Fblob\u002Fmaster\u002Fcolab\u002Ftorchaudio_SpecMasking_1_1.ipynb).\n\nMarch, 2022: We released a new preprint [*CMKD: CNN\u002FTransformer-Based Cross-Model Knowledge Distillation for Audio Classification*](https:\u002F\u002Farxiv.org\u002Fabs\u002F2203.06760), where we proposed a knowledge distillation based method to further improve the AST model performance without changing its architecture.\n\nFeb, 2022: The [Self-Supervised AST (SSAST)](https:\u002F\u002Farxiv.org\u002Fabs\u002F2110.09784) code is released [[**here**]](https:\u002F\u002Fgithub.com\u002FYuanGongND\u002Fssast). SSAST use self-supervised pretraining instead of supervised ImageNet pretraining, so it supports arbitrary patch shape and size (e.g., a temperal frame and a square patch) with a good performance.\n\nNov, 2021: The [PSLA training pipeline](https:\u002F\u002Farxiv.org\u002Fabs\u002F2102.01243) used to train AST and baseline efficientnet model code is released [[**here**]](https:\u002F\u002Fgithub.com\u002FYuanGongND\u002Fpsla). It is a strong audio classification training pipeline that can be used for most deep learning models. Also, it has a one-click FSD50K recipe that achieves SOTA 0.567 mAP.\n\n## Introduction  \n\n\u003Cp align=\"center\">\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FYuanGongND_ast_readme_90f30170464a.png\" alt=\"Illustration of AST.\" width=\"300\"\u002F>\u003C\u002Fp>\n\nThis repository contains the official implementation (in PyTorch) of the **Audio Spectrogram Transformer (AST)** proposed in the Interspeech 2021 paper [AST: Audio Spectrogram Transformer](https:\u002F\u002Farxiv.org\u002Fabs\u002F2104.01778) (Yuan Gong, Yu-An Chung, James Glass).  \n\nAST is the first **convolution-free, purely** attention-based model for audio classification which supports variable length input and can be applied to various tasks. We evaluate AST on various audio classification benchmarks, where it achieves new state-of-the-art results of 0.485 mAP on AudioSet, 95.6% accuracy on ESC-50, and 98.1% accuracy on Speech Commands V2.  For details, please refer to the paper and the [ISCA SIGML talk](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=CSRDbqGY0Vw).  \n  \nPlease have a try! AST can be used with a few lines of code, and we also provide recipes to reproduce the SOTA results on AudioSet, ESC-50, and Speechcommands with almost one click.  \n\nThe AST model file is in `src\u002Fmodels\u002Fast_models.py`, the recipes are in `egs\u002F[audioset,esc50,speechcommands]\u002Frun.sh`, when you run `run.sh`, it will call `\u002Fsrc\u002Frun.py`, which will then call `\u002Fsrc\u002Fdataloader.py` and `\u002Fsrc\u002Ftraintest.py`, which will then call `\u002Fsrc\u002Fmodels\u002Fast_models.py`.\n\nWe have an one-click, self-contained Google Colab script for (pretrained) AST inference and attention visualization. Please test the model with your own audio at [![Open In Colab](https:\u002F\u002Fcolab.research.google.com\u002Fassets\u002Fcolab-badge.svg)](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FYuanGongND\u002Fast\u002Fblob\u002Fmaster\u002Fcolab\u002FAST_Inference_Demo.ipynb) by one click (no GPU needed).\n\n## Citing  \nPlease cite our paper(s) if you find this repository useful. The first paper proposes the Audio Spectrogram Transformer while the second paper describes the training pipeline that we applied on AST to achieve the new state-of-the-art on AudioSet.   \n```  \n@inproceedings{gong21b_interspeech,\n  author={Yuan Gong and Yu-An Chung and James Glass},\n  title={{AST: Audio Spectrogram Transformer}},\n  year=2021,\n  booktitle={Proc. Interspeech 2021},\n  pages={571--575},\n  doi={10.21437\u002FInterspeech.2021-698}\n}\n```  \n```  \n@ARTICLE{gong_psla, \n    author={Gong, Yuan and Chung, Yu-An and Glass, James},  \n    journal={IEEE\u002FACM Transactions on Audio, Speech, and Language Processing},   \n    title={PSLA: Improving Audio Tagging with Pretraining, Sampling, Labeling, and Aggregation},   \n    year={2021}, \n    doi={10.1109\u002FTASLP.2021.3120633}\n}\n```  \n  \n## Getting Started  \n\nStep 1. Clone or download this repository and set it as the working directory, create a virtual environment and install the dependencies.\n\n```\ncd ast\u002F \npython3 -m venv venvast\nsource venvast\u002Fbin\u002Factivate\npip install -r requirements.txt \n```\n  \nStep 2. Test the AST model.\n\n```python\nASTModel(label_dim=527, \\\n         fstride=10, tstride=10, \\\n         input_fdim=128, input_tdim=1024, \\\n         imagenet_pretrain=True, audioset_pretrain=False, \\\n         model_size='base384')\n```  \n\n**Parameters:**\\\n`label_dim` : The number of classes (default:`527`).\\\n`fstride`:  The stride of patch spliting on the frequency dimension, for 16\\*16 patchs, fstride=16 means no overlap, fstride=10 means overlap of 6 (used in the paper). (default:`10`)\\\n`tstride`:  The stride of patch spliting on the time dimension, for 16*16 patchs, tstride=16 means no overlap, tstride=10 means overlap of 6 (used in the paper). (default:`10`)\\\n`input_fdim`: The number of frequency bins of the input spectrogram. (default:`128`)\\\n`input_tdim`: The number of time frames of the input spectrogram. (default:`1024`, i.e., 10.24s)\\\n`imagenet_pretrain`: If `True`, use ImageNet pretrained model. (default: `True`, we recommend to set it as `True` for all tasks.)\\\n`audioset_pretrain`: If`True`,  use full AudioSet And ImageNet pretrained model. Currently only support `base384` model with `fstride=tstride=10`. (default: `False`, we recommend to set it as `True` for all tasks except AudioSet.)\\\n`model_size`: The model size of AST, should be in `[tiny224, small224, base224, base384]` (default: `base384`).\n\n**Input:** Tensor in shape `[batch_size, temporal_frame_num, frequency_bin_num]`. Note: the input spectrogram should be normalized with dataset mean and std, see [here](https:\u002F\u002Fgithub.com\u002FYuanGongND\u002Fast\u002Fblob\u002F102f0477099f83e04f6f2b30a498464b78bbaf46\u002Fsrc\u002Fdataloader.py#L191). \\\n**Output:** Tensor of raw logits (i.e., without Sigmoid) in shape `[batch_size, label_dim]`.\n\n``` \ncd ast\u002Fsrc\npython\n```  \n\n```python\nimport os \nimport torch\nfrom models import ASTModel \n# download pretrained model in this directory\nos.environ['TORCH_HOME'] = '..\u002Fpretrained_models'  \n# assume each input spectrogram has 100 time frames\ninput_tdim = 100\n# assume the task has 527 classes\nlabel_dim = 527\n# create a pseudo input: a batch of 10 spectrogram, each with 100 time frames and 128 frequency bins \ntest_input = torch.rand([10, input_tdim, 128]) \n# create an AST model\nast_mdl = ASTModel(label_dim=label_dim, input_tdim=input_tdim, imagenet_pretrain=True)\ntest_output = ast_mdl(test_input) \n# output should be in shape [10, 527], i.e., 10 samples, each with prediction of 527 classes. \nprint(test_output.shape)  \n```  \n\nWe have an one-click, self-contained Google Colab script for (pretrained) AST inference and attention visualization. Please test the model with your own audio at [![Open In Colab](https:\u002F\u002Fcolab.research.google.com\u002Fassets\u002Fcolab-badge.svg)](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FYuanGongND\u002Fast\u002Fblob\u002Fmaster\u002Fcolab\u002FAST_Inference_Demo.ipynb) by one click (no GPU needed).\n\n## ESC-50 Recipe  \nThe ESC-50 recipe is in `ast\u002Fegs\u002Fesc50\u002Frun_esc.sh`, the script will automatically download the ESC-50 dataset and resample it to 16kHz, then run standard 5-cross validation and report the result.\nThe recipe was tested on 4 GTX TITAN GPUs with 12GB memory. \nThe result is saved in `ast\u002Fegs\u002Fesc50\u002Fexp\u002Fyourexpname\u002Facc_fold.csv` (the accuracy of fold 1-5 and the averaged accuracy), you can also check details in `result.csv` and `best_result.csv` (accuracy, AUC, loss, etc of each epoch \u002F best epoch).\nWe attached our log file in `ast\u002Fegs\u002Fesc50\u002Ftest-esc50-f10-t10-p-b48-lr1e-5`, the model achieves `95.75%` accuracy.\n\nTo run the recipe, simply comment out `. \u002Fdata\u002Fsls\u002Fscratch\u002Fshare-201907\u002Fslstoolchainrc` in `ast\u002Fegs\u002Fesc50\u002Frun_esc.sh`, adjust the path if needed, and run:\n``` \ncd ast\u002Fegs\u002Fesc50\n(slurm user) sbatch run_esc50.sh\n(local user) .\u002Frun_esc50.sh\n```  \n\n## Speechcommands V2 Recipe  \nThe Speechcommands recipe is in `ast\u002Fegs\u002Fspeechcommands\u002Frun_sc.sh`, the script will automatically download the Speechcommands V2 dataset, train an AST model on the training set, validate it on the validation set, and evaluate it on the test set.\nThe recipe was tested on 4 GTX TITAN GPUs with 12GB memory. \nThe result is saved in `ast\u002Fegs\u002Fspeechcommands\u002Fexp\u002Fyourexpname\u002Feval_result.csv` in format `[val_acc, val_AUC, eval_acc, eval_AUC]`, you can also check details in `result.csv` (accuracy, AUC, loss, etc of each epoch).\nWe attached our log file in `ast\u002Fegs\u002Fspeechcommends\u002Ftest-speechcommands-f10-t10-p-b128-lr2.5e-4-0.5-false`, the model achieves `98.12%` accuracy.\n\nTo run the recipe, simply comment out `. \u002Fdata\u002Fsls\u002Fscratch\u002Fshare-201907\u002Fslstoolchainrc` in `ast\u002Fegs\u002Fesc50\u002Frun_sc.sh`, adjust the path if needed, and run:\n``` \ncd ast\u002Fegs\u002Fspeechcommands\n(slurm user) sbatch run_sc.sh\n(local user) .\u002Frun_sc.sh\n```  \n\n## Audioset Recipe  \nAudioset is a little bit more complex, you will need to prepare your data json files (i.e., `train_data.json` and `eval_data.json`) by your self.\nThe reason is that the raw wavefiles of Audioset is not released and you need to download them by yourself. We have put a sample json file in `ast\u002Fegs\u002Faudioset\u002Fdata\u002Fdatafiles`, please generate files in the same format (You can also refer to `ast\u002Fegs\u002Fesc50\u002Fprep_esc50.py` and `ast\u002Fegs\u002Fspeechcommands\u002Fprep_sc.py`.). Please keep the label code consistent with `ast\u002Fegs\u002Faudioset\u002Fdata\u002Fclass_labels_indices.csv`.\n\nOnce you have the json files, you will need to generate the sampling weight file of your training data (please check our [PSLA paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F2102.01243) to see why it is needed).\n```\ncd ast\u002Fegs\u002Faudioset\npython gen_weight_file.py .\u002Fdata\u002Fdatafiles\u002Ftrain_data.json\n```\n\nThen you just need to change the `tr_data` and `te_data` in `\u002Fast\u002Fegs\u002Faudioset\u002Frun.sh` and then \n``` \ncd ast\u002Fegs\u002Faudioset\n(slurm user) sbatch run.sh\n(local user) .\u002Frun.sh\n```  \nYou should get a model achieves `0.448 mAP` (without weight averaging) and `0.459` (with weight averaging). This is the best **single** model reported in the paper. \nThe result of each epoch is saved in `ast\u002Fegs\u002Faudioset\u002Fexp\u002Fyourexpname\u002Fresult.csv` in format `[mAP, mAUC, precision, recall, d_prime, train_loss, valid_loss, cum_mAP, cum_mAUC, lr]`\n, where `cum_` results are the checkpoint ensemble results (i.e., averaging the prediction of checkpoint models of each epoch, please check our [PSLA paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F2102.01243) for details). The result of weighted averaged model is saved in `wa_result.csv` in format `[mAP, AUC, precision, recall, d-prime]`. We attached our log file in `ast\u002Fegs\u002Faudioset\u002Ftest-full-f10-t10-pTrue-b12-lr1e-5\u002F`, the model achieves `0.459` mAP.\n\nIn order to reproduce ensembe results of `0.475 mAP` and `0.485 mAP`, please train 3 models use the same setting (i.e., repeat above three times) and train 6 models with different `tstride` and `fstride`, and average the output of the models. Please refer to `ast\u002Fegs\u002Faudioset\u002Fensemble.py`. We attached our ensemble log in `\u002Fast\u002Fegs\u002Faudioset\u002Fexp\u002Fensemble-s.log` and `ensemble-m.log`. You can use our pretrained models (see below) to test ensemble result.\n\nWe use `16kHz` for our experiments. Note that you might get a slightly different result with us due to the YouTube videos are being removed with the time and your downloaded version might be different with us. We provide our evaluation audio ids in `ast\u002Fegs\u002Faudioset\u002Fdata\u002Fsanity_check\u002Four_as_eval_id.csv`. And please note that in order to compre with the PSLA paper, for the **balanced training set** experiments (with results of `0.347 mAP` and `0.378 mAP`), we use the enhanced label set (i.e., a label set that is modified by an algorithm, please see the PSLA paper for detail). So if you train with the original label set for the balanced training set, you will get a slightly worse result. However, we do not use enhanced label set for **full AudioSet experiments**, i.e., for the `0.459 mAP` (single) and `0.485 mAP` (ensemble) results, we use exactly same data and label with the official release, so you should be able to reproduce that. \n\n## Pretrained Models\nWe provide full AudioSet pretrained models and Speechcommands-V2-35 pretrained model.\n1. [Full AudioSet, 10 tstride, 10 fstride, with Weight Averaging (0.459 mAP)](https:\u002F\u002Fwww.dropbox.com\u002Fs\u002Fca0b1v2nlxzyeb4\u002Faudioset_10_10_0.4593.pth?dl=1)\n2. [Full AudioSet, 10 tstride, 10 fstride, without Weight Averaging, Model 1 (0.450 mAP)](https:\u002F\u002Fwww.dropbox.com\u002Fs\u002F1tv0hovue1bxupk\u002Faudioset_10_10_0.4495.pth?dl=1)\n3. [Full AudioSet, 10 tstride, 10 fstride, without Weight Averaging, Model 2  (0.448 mAP)](https:\u002F\u002Fwww.dropbox.com\u002Fs\u002F6u5sikl4b9wo4u5\u002Faudioset_10_10_0.4483.pth?dl=1)\n4. [Full AudioSet, 10 tstride, 10 fstride, without Weight Averaging, Model 3  (0.448 mAP)](https:\u002F\u002Fwww.dropbox.com\u002Fs\u002Fkt6i0v9fvfm1mbq\u002Faudioset_10_10_0.4475.pth?dl=1)\n5. [Full AudioSet, 12 tstride, 12 fstride, without Weight Averaging, Model (0.447 mAP)](https:\u002F\u002Fwww.dropbox.com\u002Fs\u002Fsnfhx3tizr4nuc8\u002Faudioset_12_12_0.4467.pth?dl=1)\n6. [Full AudioSet, 14 tstride, 14 fstride, without Weight Averaging, Model (0.443 mAP)](https:\u002F\u002Fwww.dropbox.com\u002Fs\u002Fz18s6pemtnxm4k7\u002Faudioset_14_14_0.4431.pth?dl=1)\n7. [Full AudioSet, 16 tstride, 16 fstride, without Weight Averaging, Model (0.442 mAP)](https:\u002F\u002Fwww.dropbox.com\u002Fs\u002Fmdsa4t1xmcimia6\u002Faudioset_16_16_0.4422.pth?dl=1)\n\n8. [Speechcommands V2-35, 10 tstride, 10 fstride, without Weight Averaging, Model (98.12% accuracy on evaluation set)](https:\u002F\u002Fwww.dropbox.com\u002Fs\u002Fq0tbqpwv44pquwy\u002Fspeechcommands_10_10_0.9812.pth?dl=1)\n\nIf you want to finetune AudioSet-pretrained AST model on your task, you can simply set the `audioset_pretrain=True` when you create the AST model, it will automatically download model 1 (`0.459 mAP`). In our ESC-50 recipe, AudioSet pretraining is used.\n\nIf you want to reproduce ensemble experiments, you can download these models at one click using `ast\u002Fegs\u002Faudioset\u002Fdownload_models.sh`. Ensemble model 2-4 achieves `0.475 mAP`, Ensemble model 2-7 achieves and `0.485 mAP`. Once you download the model, you can try `ast\u002Fegs\u002Faudioset\u002Fensemble.py`, you need to change the `eval_data_path` and `mdl_list` to run it. We attached our ensemble log in `\u002Fast\u002Fegs\u002Faudioset\u002Fexp\u002Fensemble-s.log` and `ensemble-m.log`.\n\nPlease  note that we use `16kHz` audios for training and test (for all AudioSet, SpeechCommands, and ESC-50), so if you want to use the pretrained model, please prepare your data in `16kHz`.\n\n(Note: the above links are Dropbox direct links (i.e., can be downloaded by wget) and should work for most users. For users having issue downloading with the above Dropbox links, it is recommended to use a VPN or use the [OneDrive links](https:\u002F\u002Fmitprod-my.sharepoint.com\u002F:f:\u002Fg\u002Fpersonal\u002Fyuangong_mit_edu\u002FErLKkiP-GwVMgdsCeGEjsmoBMtGvXMkX3tCj5_I0E7ikNA?e=JE9Om8) or [腾讯微云链接们](https:\u002F\u002Fshare.weiyun.com\u002FxRGK6zmg), however, OneDrive and 腾讯微云 links are not direct link, please manually download the `audioset_10_10_0.4593.pth`[[OneDrive]](https:\u002F\u002Fmitprod-my.sharepoint.com\u002F:u:\u002Fg\u002Fpersonal\u002Fyuangong_mit_edu\u002FEWrY3raql55CqxZNV3cVSkABaoU7pXQxAeJXudE1PTNzQg?e=gwEICj) [[腾讯微云]](https:\u002F\u002Fshare.weiyun.com\u002Fkcmk2KHw) and place it in `ast\u002Fpretrained_models` if you want to set `audioset_pretrain=True` because the wget link in the `ast\u002Fsrc\u002Fmodels\u002Fast_models.py` would fail if you cannot connect to Dropbox.) \n\n## Use Pretrained Model For Downstream Tasks\n\nYou can use the pretrained AST model for your own dataset. There are two ways to doing so.\n\nYou can of course only take ``ast\u002Fsrc\u002Fmodels\u002Fast_models.py``, set ``audioset_pretrain=True``, and use it with your training pipeline, the only thing need to take care of is the input normalization, we normalize our input to 0 mean and 0.5 std. To use the pretrained model, you should roughly normalize the input to this range. You can check ``ast\u002Fsrc\u002Fget_norm_stats.py`` to see how we compute the stats, or you can try using our AudioSet normalization ``input_spec = (input_spec + 4.26) \u002F (4.57 * 2)``. Using your own training pipeline might be easier if you already have a good one.\nPlease note that AST needs smaller learning rate (we use 10 times smaller learning rate than our CNN model proposed in the [PSLA paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F2102.01243)) and converges faster, so please search the learning rate and learning rate scheduler for your task. \n\nIf you want to use our training pipeline, you would need to modify below for your new dataset.\n1. You need to create a json file, and a label index for your dataset, see ``ast\u002Fegs\u002Faudioset\u002Fdata\u002F`` for an example.\n2. In ``\u002Fyour_dataset\u002Frun.sh``, you need to specify the data json file path. You need to set `dataset_mean` and `dataset_std`, if don't know, you can use our AudioSet stats (mean=-4.27, std=4.57); You need to set `audio_length`, which should be the number of frames (e.g., with a 10ms hop, 10-second audio=1000 frames); You need to set the `metrics` in [`acc`,`mAP`] and `loss` in [`CE`,`BCE`]; You need to set the inital learning rate `lr` and learning rate scheduler `lrscheduler_{start,step,decay}`;\nYou also need to set the SpecAug parameters (``freqm`` and ``timem``, we recommend to mask 48 frequency bins out of 128, and 20% of your time frames), the mixup rate (i.e., how many samples are mixup samples), batch size, etc. While it seems a lot, it is easy if you start with one of our recipe: ``ast\u002Fegs\u002F[audioset,esc50,speechcommands]\u002Frun.sh]``.\n\n[comment]: \u003C> (3. In ``ast\u002Fsrc\u002Frun.py``, line 60-65, you need to add the normalization stats, the input frame length, and if noise augmentation is needed for your dataset. Also take a look at line 101-127 if you have a seperate validation set. For normalization stats, you need to compute the mean and std of your dataset &#40;check ``ast\u002Fsrc\u002Fget_norm_stats.py``&#41; or you can try using our AudioSet normalization ``input_spec = &#40;input_spec + 4.26&#41; \u002F &#40;4.57 * 2&#41;``.)\n\n[comment]: \u003C> (4. In ``ast\u002Fsrc\u002Ftraintest.`` line 55-82, you need to specify the learning rate scheduler, metrics, warmup setting and the optimizer for your task.)\n\nTo summarize, to use our training pipeline, you need to creat data files and modify the shell script. You can refer to our ESC-50 and Speechcommands recipes.\n\nAlso, please note that we use `16kHz` audios for the pretrained model, so if you want to use the pretrained model, please prepare your data in `16kHz`.\n\n\n ## Contact\nIf you have a question, please bring up an issue (preferred) or send me an email yuangong@mit.edu.\n\n","# AST：音频谱图 Transformer  \n - [新闻](#News)\n - [简介](#Introduction)\n - [引用](#Citing)  \n - [开始使用](#Getting-Started)\n - [ESC-50 配方](#ESC-50-Recipe)  \n - [Speechcommands 配方](#Speechcommands-V2-Recipe)  \n - [AudioSet 配方](#Audioset-Recipe)\n - [预训练模型](#Pretrained-Models)\n - [将预训练模型用于下游任务](#Use-Pretrained-Model-For-Downstream-Tasks)\n - [联系方式](#Contact)\n\n## 新闻\n2023年5月：我们发布了音频大型语言模型 LTU（听、思考、理解）的演示，该模型能够进行零样本音频分类和高级推理。请尝试在线交互式演示 **[[这里]](https:\u002F\u002Fgithub.com\u002FYuanGongND\u002Fltu)**。\n\n2022年11月：我们将 `dataset` 和超参数解耦，将超参数从 `src\u002Frun.py` 和 `src\u002Ftraintest.py` 移至 `egs\u002F{audioset,esc50,speechcommands}\u002Frun.sh`，以便更轻松地将脚本适配到新数据集。这可能会导致一些问题，如果您在运行任何配方时遇到问题，请及时报告。\n\n2022年10月：我们新增了一个一键式、自包含的 Google Colab 脚本，用于进行带有注意力可视化功能的（预训练）AST 推理。您只需点击一下即可在 [![Open In Colab](https:\u002F\u002Fcolab.research.google.com\u002Fassets\u002Fcolab-badge.svg)](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FYuanGongND\u002Fast\u002Fblob\u002Fmaster\u002Fcolab\u002FAST_Inference_Demo.ipynb) 上用您自己的音频测试模型（无需 GPU）。\n\n2022年5月：发现较新的 `torchaudio` 包在 SpecAugment 方面与旧版本的行为不同，会导致一个 [bug](https:\u002F\u002Fgithub.com\u002FYuanGongND\u002Fast\u002Fissues\u002F58)。我们找到了一种解决方法并已修复。如果您感兴趣，请参阅 [这里](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FYuanGongND\u002Fast\u002Fblob\u002Fmaster\u002Fcolab\u002Ftorchaudio_SpecMasking_1_1.ipynb)。\n\n2022年3月：我们发布了一篇新的预印本 [*CMKD：基于 CNN\u002FTransformer 的跨模型知识蒸馏用于音频分类*](https:\u002F\u002Farxiv.org\u002Fabs\u002F2203.06760)，其中提出了一种基于知识蒸馏的方法，在不改变 AST 模型架构的情况下进一步提升其性能。\n\n2022年2月：[自监督 AST (SSAST)](https:\u002F\u002Farxiv.org\u002Fabs\u002F2110.09784) 的代码已发布 [[**这里**]](https:\u002F\u002Fgithub.com\u002FYuanGongND\u002Fssast)。SSAST 使用自监督预训练代替有监督的 ImageNet 预训练，因此它支持任意形状和大小的 patch（例如时间帧和方形 patch），并且表现良好。\n\n2021年11月：用于训练 AST 和基线 efficientnet 模型的 [PSLA 训练流程](https:\u002F\u002Farxiv.org\u002Fabs\u002F2102.01243) 代码已发布 [[**这里**]](https:\u002F\u002Fgithub.com\u002FYuanGongND\u002Fpsla)。这是一个强大的音频分类训练流程，可用于大多数深度学习模型。此外，它还提供了一个一键式的 FSD50K 配方，可达到 SOTA 0.567 mAP 的成绩。\n\n## 简介  \n\n\u003Cp align=\"center\">\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FYuanGongND_ast_readme_90f30170464a.png\" alt=\"AST 示意图.\" width=\"300\"\u002F>\u003C\u002Fp>\n\n本仓库包含了 Interspeech 2021 论文 [AST：音频谱图 Transformer](https:\u002F\u002Farxiv.org\u002Fabs\u002F2104.01778)（Yuan Gong、Yu-An Chung、James Glass）中提出的 **音频谱图 Transformer (AST)** 的官方 PyTorch 实现。  \n\nAST 是首个 **无卷积、纯** 注意力驱动的音频分类模型，支持变长输入，并可应用于多种任务。我们在多个音频分类基准上评估了 AST，结果表明它在 AudioSet 上达到了 0.485 mAP 的新 SOTA 成绩，在 ESC-50 上准确率为 95.6%，在 Speech Commands V2 上准确率为 98.1%。更多详情请参阅论文及 [ISCA SIGML 演讲](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=CSRDbqGY0Vw)。  \n  \n欢迎您试用！AST 只需几行代码即可使用，我们还提供了配方，几乎一键就能复现 AudioSet、ESC-50 和 Speechcommands 上的 SOTA 结果。  \n\nAST 模型文件位于 `src\u002Fmodels\u002Fast_models.py`，配方位于 `egs\u002F[audioset,esc50,speechcommands]\u002Frun.sh`。当您运行 `run.sh` 时，它会调用 `\u002Fsrc\u002Frun.py`，后者再调用 `\u002Fsrc\u002Fdataloader.py` 和 `\u002Fsrc\u002Ftraintest.py`，最终这些文件会调用 `\u002Fsrc\u002Fmodels\u002Fast_models.py`。\n\n我们还有一个一键式、自包含的 Google Colab 脚本，用于进行（预训练）AST 推理和注意力可视化。请通过 [![Open In Colab](https:\u002F\u002Fcolab.research.google.com\u002Fassets\u002Fcolab-badge.svg)](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FYuanGongND\u002Fast\u002Fblob\u002Fmaster\u002Fcolab\u002FAST_Inference_Demo.ipynb) 一键测试模型，使用您自己的音频（无需 GPU）。\n\n## 引用  \n如果您觉得本仓库有用，请引用我们的论文。第一篇论文提出了音频谱图 Transformer，而第二篇论文则描述了我们应用于 AST 以在 AudioSet 上取得新 SOTA 成绩的训练流程。   \n```  \n@inproceedings{gong21b_interspeech,\n  author={Yuan Gong and Yu-An Chung and James Glass},\n  title={{AST: Audio Spectrogram Transformer}},\n  year=2021,\n  booktitle={Proc. Interspeech 2021},\n  pages={571--575},\n  doi={10.21437\u002FInterspeech.2021-698}\n}\n```  \n```  \n@ARTICLE{gong_psla, \n    author={Gong, Yuan and Chung, Yu-An and Glass, James},  \n    journal={IEEE\u002FACM Transactions on Audio, Speech, and Language Processing},   \n    title={PSLA：通过预训练、采样、标注和聚合改进音频标记},   \n    year={2021}, \n    doi={10.1109\u002FTASLP.2021.3120633}\n}\n```\n\n## 入门指南  \n\n步骤 1. 克隆或下载此仓库，并将其设置为工作目录，创建虚拟环境并安装依赖项。\n\n```\ncd ast\u002F \npython3 -m venv venvast\nsource venvast\u002Fbin\u002Factivate\npip install -r requirements.txt \n```\n  \n步骤 2. 测试 AST 模型。\n\n```python\nASTModel(label_dim=527, \\\n         fstride=10, tstride=10, \\\n         input_fdim=128, input_tdim=1024, \\\n         imagenet_pretrain=True, audioset_pretrain=False, \\\n         model_size='base384')\n```  \n\n**参数说明：**  \n`label_dim`：类别数量（默认值：`527`）。  \n`fstride`：频率维度上补丁分割的步长。对于 16×16 的补丁，`fstride=16` 表示无重叠，`fstride=10` 表示有 6 的重叠（论文中采用的设置）。（默认值：`10`）  \n`tstride`：时间维度上补丁分割的步长。对于 16×16 的补丁，`tstride=16` 表示无重叠，`tstride=10` 表示有 6 的重叠（论文中采用的设置）。（默认值：`10`）  \n`input_fdim`：输入谱图的频率通道数。（默认值：`128`）  \n`input_tdim`：输入谱图的时间帧数。（默认值：`1024`，即 10.24 秒）  \n`imagenet_pretrain`：若为 `True`，则使用 ImageNet 预训练模型。（默认值：`True`，我们建议在所有任务中都设置为 `True`）  \n`audioset_pretrain`：若为 `True`，则使用 AudioSet 和 ImageNet 的联合预训练模型。目前仅支持 `fstride=tstride=10` 的 `base384` 模型。（默认值：`False`，我们建议除 AudioSet 任务外，在其他任务中都设置为 `True`）  \n`model_size`：AST 模型的大小，应为 `[tiny224, small224, base224, base384]` 中的一个（默认值：`base384`）。\n\n**输入：** 形状为 `[batch_size, temporal_frame_num, frequency_bin_num]` 的张量。注意：输入谱图应使用数据集的均值和标准差进行归一化，请参阅 [此处](https:\u002F\u002Fgithub.com\u002FYuanGongND\u002Fast\u002Fblob\u002F102f0477099f83e04f6f2b30a498464b78bbaf46\u002Fsrc\u002Fdataloader.py#L191)。  \n**输出：** 形状为 `[batch_size, label_dim]` 的原始 logits 张量（即未经过 Sigmoid 激活函数处理）。\n\n``` \ncd ast\u002Fsrc\npython\n```  \n\n```python\nimport os \nimport torch\nfrom models import ASTModel \n# 在此目录下下载预训练模型\nos.environ['TORCH_HOME'] = '..\u002Fpretrained_models'  \n# 假设每个输入谱图有 100 个时间帧\ninput_tdim = 100\n# 假设任务有 527 个类别\nlabel_dim = 527\n# 创建一个伪输入：一批 10 张谱图，每张有 100 个时间帧和 128 个频率通道 \ntest_input = torch.rand([10, input_tdim, 128]) \n# 创建一个 AST 模型\nast_mdl = ASTModel(label_dim=label_dim, input_tdim=input_tdim, imagenet_pretrain=True)\ntest_output = ast_mdl(test_input) \n# 输出应为形状 [10, 527]，即 10 个样本，每个样本包含 527 个类别的预测结果。 \nprint(test_output.shape)  \n```  \n\n我们提供了一个一键式、自包含的 Google Colab 脚本，用于（预训练）AST 推理及注意力可视化。请通过点击 [![Open In Colab](https:\u002F\u002Fcolab.research.google.com\u002Fassets\u002Fcolab-badge.svg)](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FYuanGongND\u002Fast\u002Fblob\u002Fmaster\u002Fcolab\u002FAST_Inference_Demo.ipynb)，使用您自己的音频测试该模型（无需 GPU）。\n\n## ESC-50 使用流程  \nESC-50 的使用流程位于 `ast\u002Fegs\u002Fesc50\u002Frun_esc.sh`，该脚本会自动下载 ESC-50 数据集并将其重采样至 16kHz，随后执行标准的 5 折交叉验证并报告结果。\n该流程已在配备 12GB 显存的 4 张 GTX TITAN 显卡上测试完成。\n结果保存在 `ast\u002Fegs\u002Fesc50\u002Fexp\u002Fyourexpname\u002Facc_fold.csv` 中（包括第 1 至 5 折的准确率及平均准确率），您还可以在 `result.csv` 和 `best_result.csv` 中查看详细信息（各轮次\u002F最佳轮次的准确率、AUC、损失等）。\n我们附上了日志文件 `ast\u002Fegs\u002Fesc50\u002Ftest-esc50-f10-t10-p-b48-lr1e-5`，该模型达到了 `95.75%` 的准确率。\n\n要运行该流程，只需在 `ast\u002Fegs\u002Fesc50\u002Frun_esc.sh` 中注释掉 `. \u002Fdata\u002Fsls\u002Fscratch\u002Fshare-201907\u002Fslstoolchainrc`，如有需要可调整路径，然后执行：\n``` \ncd ast\u002Fegs\u002Fesc50\n（Slurm 用户） sbatch run_esc50.sh\n（本地用户） .\u002Frun_esc50.sh\n```  \n\n## Speechcommands V2 使用流程  \nSpeechcommands V2 的使用流程位于 `ast\u002Fegs\u002Fspeechcommands\u002Frun_sc.sh`，该脚本会自动下载 Speechcommands V2 数据集，在训练集上训练 AST 模型，在验证集上进行验证，并在测试集上进行评估。\n该流程已在配备 12GB 显存的 4 张 GTX TITAN 显卡上测试完成。\n结果保存在 `ast\u002Fegs\u002Fspeechcommands\u002Fexp\u002Fyourexpname\u002Feval_result.csv` 中，格式为 `[val_acc, val_AUC, eval_acc, eval_AUC]`，您还可以在 `result.csv` 中查看详细信息（各轮次的准确率、AUC、损失等）。\n我们附上了日志文件 `ast\u002Fegs\u002Fspeechcommends\u002Ftest-speechcommands-f10-t10-p-b128-lr2.5e-4-0.5-false`，该模型达到了 `98.12%` 的准确率。\n\n要运行该流程，只需在 `ast\u002Fegs\u002Fesc50\u002Frun_sc.sh` 中注释掉 `. \u002Fdata\u002Fsls\u002Fscratch\u002Fshare-201907\u002Fslstoolchainrc`，如有需要可调整路径，然后执行：\n``` \ncd ast\u002Fegs\u002Fspeechcommands\n（Slurm 用户） sbatch run_sc.sh\n（本地用户） .\u002Frun_sc.sh\n```\n\n## Audioset 配方  \nAudioset 的配置稍微复杂一些，您需要自行准备数据的 JSON 文件（即 `train_data.json` 和 `eval_data.json`）。原因是 Audioset 的原始音频文件并未公开，需由您自行下载。我们已在 `ast\u002Fegs\u002Faudioset\u002Fdata\u002Fdatafiles` 中提供了一个示例 JSON 文件，请按照相同格式生成文件（您也可以参考 `ast\u002Fegs\u002Fesc50\u002Fprep_esc50.py` 和 `ast\u002Fegs\u002Fspeechcommands\u002Fprep_sc.py`）。请确保标签编码与 `ast\u002Fegs\u002Faudioset\u002Fdata\u002Fclass_labels_indices.csv` 保持一致。\n\n准备好 JSON 文件后，您还需要为训练数据生成采样权重文件（请参阅我们的 [PSLA 论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F2102.01243)，了解为何需要该文件）：\n```\ncd ast\u002Fegs\u002Faudioset\npython gen_weight_file.py .\u002Fdata\u002Fdatafiles\u002Ftrain_data.json\n```\n\n随后，只需修改 `\u002Fast\u002Fegs\u002Faudioset\u002Frun.sh` 中的 `tr_data` 和 `te_data`，然后执行以下命令：\n``` \ncd ast\u002Fegs\u002Faudioset\n（Slurm 用户） sbatch run.sh\n（本地用户） .\u002Frun.sh\n```  \n您应该能够得到一个模型，其 mAP 分别为 `0.448`（未加权平均）和 `0.459`（加权平均）。这是论文中报道的最佳 **单模型** 结果。  \n\n每个 epoch 的结果会以 `[mAP, mAUC, precision, recall, d_prime, train_loss, valid_loss, cum_mAP, cum_mAUC, lr]` 的格式保存在 `ast\u002Fegs\u002Faudioset\u002Fexp\u002Fyourexpname\u002Fresult.csv` 中，其中 `cum_` 结果是检查点集成的结果（即对每个 epoch 的检查点模型预测进行平均，请参阅我们的 [PSLA 论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F2102.01243) 获取详细信息）。加权平均模型的结果则会以 `[mAP, AUC, precision, recall, d-prime]` 的格式保存在 `wa_result.csv` 中。我们在 `ast\u002Fegs\u002Faudioset\u002Ftest-full-f10-t10-pTrue-b12-lr1e-5\u002F` 中附上了我们的日志文件，该模型达到了 `0.459` 的 mAP。\n\n为了复现 `0.475 mAP` 和 `0.485 mAP` 的集成结果，请使用相同的设置训练 3 个模型（即重复上述步骤三次），并再用不同的 `tstride` 和 `fstride` 训练 6 个模型，最后对这些模型的输出进行平均。具体操作请参考 `ast\u002Fegs\u002Faudioset\u002Fensemble.py`。我们已将集成日志分别存放在 `\u002Fast\u002Fegs\u002Faudioset\u002Fexp\u002Fensemble-s.log` 和 `ensemble-m.log` 中。您也可以使用我们提供的预训练模型来测试集成效果。\n\n我们的实验均采用 `16kHz` 的采样率。请注意，由于 YouTube 视频会随时间被移除，您下载的数据版本可能与我们的不同，因此可能会得到略微差异的结果。我们在 `ast\u002Fegs\u002Faudioset\u002Fdata\u002Fsanity_check\u002Four_as_eval_id.csv` 中提供了用于评估的音频 ID 列表。此外，请注意，为了与 PSLA 论文中的结果进行对比，在 **平衡训练集** 实验中（结果分别为 `0.347 mAP` 和 `0.378 mAP`），我们使用了增强标签集（即通过算法修改后的标签集，详情请参阅 PSLA 论文）。因此，如果您使用原始标签集进行平衡训练集的训练，结果可能会稍差。然而，在 **完整 Audioset 实验** 中，即 `0.459 mAP`（单模型）和 `0.485 mAP`（集成模型）的结果中，我们使用的数据和标签与官方发布的完全一致，因此您应该能够复现这些结果。\n\n## 预训练模型  \n我们提供了完整的 Audioset 预训练模型以及 Speechcommands-V2-35 的预训练模型。  \n1. [完整 Audioset，10 tstride，10 fstride，加权平均（0.459 mAP）](https:\u002F\u002Fwww.dropbox.com\u002Fs\u002Fca0b1v2nlxzyeb4\u002Faudioset_10_10_0.4593.pth?dl=1)  \n2. [完整 Audioset，10 tstride，10 fstride，不加权平均，模型 1（0.450 mAP）](https:\u002F\u002Fwww.dropbox.com\u002Fs\u002F1tv0hovue1bxupk\u002Faudioset_10_10_0.4495.pth?dl=1)  \n3. [完整 Audioset，10 tstride，10 fstride，不加权平均，模型 2（0.448 mAP）](https:\u002F\u002Fwww.dropbox.com\u002Fs\u002F6u5sikl4b9wo4u5\u002Faudioset_10_10_0.4483.pth?dl=1)  \n4. [完整 Audioset，10 tstride，10 fstride，不加权平均，模型 3（0.448 mAP）](https:\u002F\u002Fwww.dropbox.com\u002Fs\u002Fkt6i0v9fvfm1mbq\u002Faudioset_10_10_0.4475.pth?dl=1)  \n5. [完整 Audioset，12 tstride，12 fstride，不加权平均，模型（0.447 mAP）](https:\u002F\u002Fwww.dropbox.com\u002Fs\u002Fsnfhx3tizr4nuc8\u002Faudioset_12_12_0.4467.pth?dl=1)  \n6. [完整 Audioset，14 tstride，14 fstride，不加权平均，模型（0.443 mAP）](https:\u002F\u002Fwww.dropbox.com\u002Fs\u002Fz18s6pemtnxm4k7\u002Faudioset_14_14_0.4431.pth?dl=1)  \n7. [完整 Audioset，16 tstride，16 fstride，不加权平均，模型（0.442 mAP）](https:\u002F\u002Fwww.dropbox.com\u002Fs\u002Fmdsa4t1xmcimia6\u002Faudioset_16_16_0.4422.pth?dl=1)\n\n8. [Speechcommands V2-35，10 tstride，10 fstride，不加权平均，模型（在评估集上准确率为 98.12%）](https:\u002F\u002Fwww.dropbox.com\u002Fs\u002Fq0tbqpwv44pquwy\u002Fspeechcommands_10_10_0.9812.pth?dl=1)\n\n如果您希望在自己的任务上微调 Audioset 预训练的 AST 模型，只需在创建 AST 模型时将 `audioset_pretrain=True` 设置即可，系统会自动下载模型 1（0.459 mAP）。在我们的 ESC-50 配方中，就使用了 Audioset 的预训练。\n\n若想复现集成实验，您可以使用 `ast\u002Fegs\u002Faudioset\u002Fdownload_models.sh` 脚本一键下载这些模型。集成模型 2–4 可达到 `0.475 mAP`，而集成模型 2–7 则可达到 `0.485 mAP`。下载完成后，您可以尝试运行 `ast\u002Fegs\u002Faudioset\u002Fensemble.py`，只需修改 `eval_data_path` 和 `mdl_list` 即可运行。我们已将集成日志分别存放在 `\u002Fast\u002Fegs\u002Faudioset\u002Fexp\u002Fensemble-s.log` 和 `ensemble-m.log` 中。\n\n请注意，我们用于训练和测试的音频均采用 `16kHz` 采样率（适用于所有 Audioset、SpeechCommands 和 ESC-50 数据集），因此如果您要使用预训练模型，请务必确保您的数据也采用 `16kHz` 采样率。  \n\n（注：以上链接均为 Dropbox 直链（可通过 wget 下载），大多数用户均可正常使用。对于无法通过上述 Dropbox 链接下载的用户，建议使用 VPN 或者访问 [OneDrive 链接](https:\u002F\u002Fmitprod-my.sharepoint.com\u002F:f:\u002Fg\u002Fpersonal\u002Fyuangong_mit_edu\u002FErLKkiP-GwVMgdsCeGEjsmoBMtGvXMkX3tCj5_I0E7ikNA?e=JE9Om8) 或 [腾讯微云链接](https:\u002F\u002Fshare.weiyun.com\u002FxRGK6zmg)。不过，OneDrive 和腾讯微云的链接并非直链，您需要手动下载 `audioset_10_10_0.4593.pth`[[OneDrive]](https:\u002F\u002Fmitprod-my.sharepoint.com\u002F:u:\u002Fg\u002Fpersonal\u002Fyuangong_mit_edu\u002FEWrY3raql55CqxZNV3cVSkABaoU7pXQxAeJXudE1PTNzQg?e=gwEICj) [[腾讯微云]](https:\u002F\u002Fshare.weiyun.com\u002Fkcmk2KHw)，并将其放置在 `ast\u002Fpretrained_models` 目录下，以便在设置 `audioset_pretrain=True` 时正常工作，因为如果无法连接到 Dropbox，`ast\u002Fsrc\u002Fmodels\u002Fast_models.py` 中的 wget 链接将会失败。）\n\n## 使用预训练模型进行下游任务\n\n您可以将预训练的 AST 模型应用于您自己的数据集。有两种方法可以实现这一点。\n\n当然，您也可以只使用 `ast\u002Fsrc\u002Fmodels\u002Fast_models.py`，将 `audioset_pretrain=True` 设置为真，并将其与您自己的训练流程一起使用。需要注意的是输入归一化问题：我们对输入进行了归一化处理，使其均值为 0、标准差为 0.5。为了使用预训练模型，您应该大致将输入归一化到这个范围。您可以查看 `ast\u002Fsrc\u002Fget_norm_stats.py` 了解我们如何计算这些统计量，或者直接使用我们的 AudioSet 归一化公式：`input_spec = (input_spec + 4.26) \u002F (4.57 * 2)`。如果您已经有一个成熟的训练流程，那么直接使用它可能会更方便。\n\n请注意，AST 需要较小的学习率（我们使用的学习率是 [PSLA 论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F2102.01243) 中提出的 CNN 模型的十分之一），并且收敛速度更快。因此，请针对您的任务搜索合适的学习率和学习率调度策略。\n\n如果您希望使用我们的训练流程，则需要根据您的新数据集进行以下修改：\n\n1. 您需要为您的数据集创建一个 JSON 文件以及标签索引，可以参考 `ast\u002Fegs\u002Faudioset\u002Fdata\u002F` 中的示例。\n2. 在 `\u002Fyour_dataset\u002Frun.sh` 中，您需要指定数据 JSON 文件的路径。此外，您还需要设置 `dataset_mean` 和 `dataset_std`；如果不确定，可以使用我们的 AudioSet 统计值（均值=-4.27，标准差=4.57）。您还需设置 `audio_length`，即音频的帧数（例如，以 10ms 的步长，10 秒的音频等于 1000 帧）。同时，您需要在 `metrics` 中选择 `[acc, mAP]`，在 `loss` 中选择 `[CE, BCE]`。此外，您还需要设置初始学习率 `lr` 和学习率调度器 `lrscheduler_{start, step, decay}`。\n\n您还需要设置 SpecAug 参数（`freqm` 和 `timem`，我们建议掩码掉 128 个频段中的 48 个频段，以及 20% 的时间帧）、mixup 比例（即 mixup 样本的比例）、批量大小等。虽然看起来步骤较多，但如果您从我们的现有配方之一开始——`ast\u002Fegs\u002F[audioset, esc50, speechcommands]\u002Frun.sh`——就会变得非常简单。\n\n[注释]：3. 在 `ast\u002Fsrc\u002Frun.py` 的第 60–65 行，您需要添加归一化统计信息、输入帧长度，以及是否需要为您的数据集添加噪声增强。如果您有单独的验证集，请同时查看第 101–127 行。对于归一化统计信息，您需要计算数据集的均值和标准差（请参考 `ast\u002Fsrc\u002Fget_norm_stats.py`），或者直接使用我们的 AudioSet 归一化公式：`input_spec = (input_spec + 4.26) \u002F (4.57 * 2)`。\n\n[注释]：4. 在 `ast\u002Fsrc\u002Ftraintest.py` 的第 55–82 行，您需要为您的任务指定学习率调度器、评估指标、warmup 设置以及优化器。\n\n总结来说，要使用我们的训练流程，您需要创建数据文件并修改 Shell 脚本。您可以参考我们的 ESC-50 和 Speechcommands 配方。\n\n另外，请注意，我们用于预训练的音频采样率为 `16kHz`，因此如果您想使用该预训练模型，也请确保您的数据是以 `16kHz` 采样率准备的。\n\n## 联系方式\n如果您有任何问题，欢迎提交 Issue（推荐）或发送邮件至 yuangong@mit.edu。","# AST (Audio Spectrogram Transformer) 快速上手指南\n\nAST 是首个完全基于注意力机制（无卷积）的音频分类模型，支持可变长度输入，在 AudioSet、ESC-50 和 Speech Commands V2 等基准测试中取得了最先进的结果。\n\n## 环境准备\n\n*   **操作系统**: Linux \u002F macOS (Windows 用户建议使用 WSL2 或 Docker)\n*   **Python**: 3.7+\n*   **核心依赖**: PyTorch, torchaudio\n*   **硬件要求**:\n    *   **推理**: 无需 GPU，CPU 即可运行。\n    *   **训练\u002F复现 SOTA**: 建议配备 NVIDIA GPU (原文测试环境为 4x GTX TITAN 12GB)。\n\n## 安装步骤\n\n1.  **克隆仓库并进入目录**\n    ```bash\n    git clone https:\u002F\u002Fgithub.com\u002FYuanGongND\u002Fast.git\n    cd ast\n    ```\n\n2.  **创建虚拟环境并安装依赖**\n    ```bash\n    python3 -m venv venvast\n    source venvast\u002Fbin\u002Factivate\n    pip install -r requirements.txt\n    ```\n    > **提示**: 国内用户若下载依赖较慢，可添加清华源加速：\n    > `pip install -r requirements.txt -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple`\n\n## 基本使用\n\n以下示例展示如何加载预训练模型并进行简单的推理测试。\n\n### 1. 代码示例\n\n创建一个 Python 脚本（例如 `test_ast.py`），填入以下代码：\n\n```python\nimport os \nimport torch\nfrom src.models import ASTModel \n\n# 设置预训练模型下载目录 (模型将自动下载到 ..\u002Fpretrained_models)\nos.environ['TORCH_HOME'] = '..\u002Fpretrained_models'  \n\n# 参数配置\ninput_tdim = 100       # 输入频谱的时间帧数 (假设每段音频有 100 帧)\nlabel_dim = 527        # 分类类别数量 (AudioSet 为 527 类)\n\n# 构造伪输入数据: [batch_size, time_frames, freq_bins]\n# 注意：实际使用时，输入频谱需使用数据集的均值和标准差进行归一化\ntest_input = torch.rand([10, input_tdim, 128]) \n\n# 初始化 AST 模型\n# imagenet_pretrain=True: 使用 ImageNet 预训练权重 (推荐用于所有任务)\n# audioset_pretrain=False: 若需使用 AudioSet+ImageNet 联合预训练模型，设为 True (仅支持 base384)\nast_mdl = ASTModel(\n    label_dim=label_dim, \n    input_tdim=input_tdim, \n    imagenet_pretrain=True,\n    model_size='base384'\n)\n\n# 执行推理\ntest_output = ast_mdl(test_input) \n\n# 输出形状应为 [10, 527]，即 10 个样本，每个样本对应 527 类的预测 logits\nprint(f\"Output shape: {test_output.shape}\")\n```\n\n### 2. 运行测试\n\n确保在激活的虚拟环境中运行：\n\n```bash\ncd ast\u002Fsrc\npython ..\u002Ftest_ast.py\n```\n\n### 3. 在线体验 (无需本地安装)\n\n如果您想快速测试模型效果或可视化注意力图，可以使用官方提供的 Google Colab 脚本（无需本地 GPU）：\n[AST Inference Demo on Colab](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FYuanGongND\u002Fast\u002Fblob\u002Fmaster\u002Fcolab\u002FAST_Inference_Demo.ipynb)\n\n---\n**关键参数说明：**\n*   `label_dim`: 类别数量。\n*   `fstride` \u002F `tstride`: 频域和时域的 Patch 步长（默认 10，表示有重叠）。\n*   `input_fdim`: 输入频谱的频带数（默认 128）。\n*   `model_size`: 模型大小，可选 `[tiny224, small224, base224, base384]`。","某智能安防团队正在开发一套城市声景监测系统，需要自动识别街道上的异常声音（如玻璃破碎、汽车急刹或警笛）以触发预警。\n\n### 没有 ast 时\n- 依赖传统 CNN 模型处理音频，必须将不同长度的录音强行裁剪或填充为固定时长，导致关键声音特征丢失或引入大量无效噪声。\n- 模型架构中混杂了大量卷积层，难以捕捉音频频谱图中的长距离时间依赖关系，对复杂背景音下的突发异响识别率低下。\n- 复现业界最优效果极其困难，缺乏统一的训练流水线，团队需花费数周时间手动调整数据增强策略和超参数。\n- 迁移到新场景成本高，每次更换数据集都需要从头训练模型，无法利用已有的大规模音频预训练知识。\n\n### 使用 ast 后\n- 利用 AST 纯注意力机制的特性，直接输入可变长度的音频频谱图，完整保留声音事件的时序特征，无需担心裁剪带来的信息损失。\n- 作为首个无卷积的纯注意力音频模型，AST 能精准捕捉全局上下文关联，在嘈杂街道背景下对玻璃破碎等细微异常的识别准确率显著提升。\n- 调用官方提供的 ESC-50 或 AudioSet 复现脚本，一键即可加载预训练权重并微调，几天内便能达到论文所述的 SOTA（最先进）性能指标。\n- 借助强大的预训练模型进行下游任务迁移，仅需少量标注数据即可适应新的监控场景，大幅降低了数据采集和模型训练成本。\n\nAST 通过纯注意力架构和开箱即用的预训练模型，让开发者能以极低门槛构建高精度、自适应的音频分类系统。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FYuanGongND_ast_014d5b1e.png","YuanGongND","Yuan Gong","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002FYuanGongND_419028d1.jpg","Research Scientist, MIT CSAIL","MIT","Cambridge, MA","yuangongfdu@gmail.com",null,"yuangongnd.github.io","https:\u002F\u002Fgithub.com\u002FYuanGongND",[84,88,92],{"name":85,"color":86,"percentage":87},"Jupyter Notebook","#DA5B0B",88.3,{"name":89,"color":90,"percentage":91},"Python","#3572A5",10.7,{"name":93,"color":94,"percentage":95},"Shell","#89e051",0.9,1447,244,"2026-04-09T03:58:28","BSD-3-Clause","Linux","训练需要 NVIDIA GPU (测试环境为 4 张 GTX TITAN, 每张 12GB 显存); 推理可使用 CPU (Google Colab 演示无需 GPU)","未说明",{"notes":104,"python":105,"dependencies":106},"1. 训练 ESC-50 和 SpeechCommands 数据集建议使用 4 张 12GB 显存的 GPU。2. torchaudio 新版本在 SpecAugment 行为上与旧版本不同，可能导致 bug，项目已提供解决方案。3. AudioSet 数据集需用户自行准备波形文件和 JSON 标签文件。4. 提供一键运行的 Google Colab 脚本用于推理和注意力可视化，无需本地 GPU。5. 需通过 pip install -r requirements.txt 安装依赖。","3.x (README 示例使用 python3)",[107,108,109,110,111,112,113,114],"torch","torchaudio","numpy","scipy","librosa","pandas","tqdm","tensorboard",[116,14],"音频",[118,119,120,121,122,123,124,125],"pytorch","audio-classification","deep-learning","audio","representation-learning","keyword-spotting","speech-commands","speech-classification","2026-03-27T02:49:30.150509","2026-04-11T00:49:39.001826",[129,134,139,144,148,153,158],{"id":130,"question_zh":131,"answer_zh":132,"source_url":133},28619,"使用 AudioSet 预训练模型时出现位置嵌入（positional embedding）重塑错误怎么办？","该错误通常发生在输入的时间维度（input_tdim）与预训练模型不匹配时。AudioSet 预训练模型默认基于特定的时间帧数（如 1024 或特定 patch 数量）。如果自定义输入的 `input_tdim` 导致计算出的 patch 数量与预训练权重不一致，就会报错。\n\n解决方案：\n1. 确保输入频谱图的尺寸与模型预期一致。例如，尝试将 `input_tdim` 设置为 100，`input_fdim` 设置为 64。\n2. 如果必须使用不同尺寸，可能需要禁用 AudioSet 预训练（设置 `audioset_pretrain=False`），或者手动调整位置嵌入层的形状以匹配新的输入尺寸。\n3. 参考以下代码示例进行初始化：\n```python\ninput_tdim = 100\ninput_fdim = 64\nast_mdl = ASTModel(input_tdim=input_tdim, input_fdim=input_fdim, label_dim=50, audioset_pretrain=True, imagenet_pretrain=True)\n```","https:\u002F\u002Fgithub.com\u002FYuanGongND\u002Fast\u002Fissues\u002F27",{"id":135,"question_zh":136,"answer_zh":137,"source_url":138},28620,"为什么在 Speech Commands 数据集上要添加随机噪声和时间移位（random noise\u002Ftime-shift）？","添加随机噪声和时间移位是一种数据增强策略，主要用于防止过拟合，特别是在训练数据量较小的情况下。\n\n维护者解释：\n1. **数据量的影响**：当训练集样本数量较少时，数据增强的益处最大；随着数据量增加，其相对收益会降低。\n2. **作用机制**：对于短时音频（如语音命令），微小的时间移位或背景噪声模拟了真实环境的变化，迫使模型学习更鲁棒的特征，而不是死记硬背训练样本。\n3. **代码实现**：在 `dataloader.py` 中通过 `torch.roll` 实现时间移位，这是一种简单有效的增强手段。","https:\u002F\u002Fgithub.com\u002FYuanGongND\u002Fast\u002Fissues\u002F79",{"id":140,"question_zh":141,"answer_zh":142,"source_url":143},28621,"AST 模型中的 Transformer 或注意力机制体现在哪里？","AST 模型基于 Vision Transformer (ViT) 架构，其核心注意力机制封装在底层使用的 `timm` 库的 DeiT 模型中。\n\n具体查找位置：\n1. 模型定义通常在 `ast_models.py` 中，它会调用 `timm` 创建的骨干网络。\n2. 注意力层（Attention layers）和 Transformer 块并不直接以显式的 `class Attention` 形式写在 AST 的主文件中，而是继承自 `timm.models.vision_transformer`。\n3. 如果需要查看具体实现，请检查 `timm` 库中关于 DeiT 或 ViT 的源码，AST 主要是对音频频谱图进行了 Patch 嵌入处理，然后送入标准的 Transformer 编码器。","https:\u002F\u002Fgithub.com\u002FYuanGongND\u002Fast\u002Fissues\u002F10",{"id":145,"question_zh":146,"answer_zh":147,"source_url":143},28622,"复现论文结果时，验证集准确率低于预期（例如只有 0.974 而不是 0.981）是什么原因？","准确率略低通常是由训练轮数（epochs）不足或随机种子差异引起的。\n\n排查步骤：\n1. **检查训练轮数**：确保你训练的 epoch 数量与论文配方一致。例如，Speech Commands 任务的官方配置通常需要训练 30 个 epoch。如果在第 10 个 epoch 停止，准确率自然会低于最终收敛值（日志显示第 10 个 epoch 时验证准确率约为 0.974，这与你的结果吻合）。\n2. **超参数一致性**：严格对照官方提供的 `log.txt` 或配置文件，确保学习率、batch size 等超参数完全一致。\n3. **随机性**：深度学习训练存在随机噪声，单次运行结果可能在均值附近波动。论文报告的是多次运行的平均值±标准差，单次运行稍高或稍低均属正常。",{"id":149,"question_zh":150,"answer_zh":151,"source_url":152},28623,"加载检查点（checkpoint）进行推理时，出现 `pos_embed` 尺寸不匹配错误如何解决？","该错误表明当前模型的输入尺寸与保存检查点时的输入尺寸不一致，导致位置嵌入（positional embedding）的形状无法匹配。\n\n原因分析：\n错误信息 `size mismatch for module.v.pos_embed` 指出，检查点中的位置嵌入形状（例如 `[1, 602, 768]`）与当前初始化的模型形状（例如 `[1, 1214, 768]`）不同。这通常是因为推理时的音频长度或频谱图裁剪方式与训练时不同。\n\n解决方案：\n1. **统一特征提取流程**：确保推理阶段生成频谱图（fbank）的参数（如 `fstride`, `tstride`, 裁剪长度）与训练阶段完全一致。\n2. **固定输入长度**：在推理前，将音频填充或裁剪到与训练时相同的时长，以保证生成的频谱图时间帧数（time frames）一致。\n3. **检查数据处理代码**：重点检查 `feature making part`（特征制作部分），确保没有意外改变输入张量的维度。","https:\u002F\u002Fgithub.com\u002FYuanGongND\u002Fast\u002Fissues\u002F26",{"id":154,"question_zh":155,"answer_zh":156,"source_url":157},28624,"如何将 AST 模型用于自定义的下游任务（如二分类）并避免维度错误？","在自定义下游任务时，需特别注意输入张量维度与预训练权重的匹配。\n\n常见问题与解决：\n1. **维度不匹配**：如果出现 `RuntimeError: The size of tensor a must match the size of tensor b`，通常是因为输入频谱图的时间帧数导致的 Patch 数量与模型内部位置嵌入不匹配。\n2. **配置建议**：\n   - 对于二分类，设置 `label_dim=1`。\n   - 如果使用 ImageNet 预训练，设置 `imagenet_pretrain=True`；若使用 AudioSet 预训练，需确保输入尺寸符合 AudioSet 的训练规范（通常涉及特定的时间\u002F频率步长）。\n   - 尝试调整 `input_tdim`，不要直接使用音频的最大持续时间乘以 100，而应参考预训练模型的接受范围，或者先尝试不使用预训练权重（`audioset_pretrain=False`）来调试形状问题。\n3. **策略调整**：如果音频长度变化大，建议使用滑动窗口生成频谱图，但需注意这会显著增加数据量；或者统一将所有音频重采样并裁剪\u002F填充到固定长度。","https:\u002F\u002Fgithub.com\u002FYuanGongND\u002Fast\u002Fissues\u002F53",{"id":159,"question_zh":160,"answer_zh":161,"source_url":152},28625,"如何在 AST 框架中使用 timm 包中的其他视觉模型（非 DeiT）？","虽然可以替换骨干网络，但需要修改源代码以适应不同模型的结构差异。\n\n具体步骤：\n1. **修改 ast_models.py**：你需要更改实例化模型的代码，引入 `timm` 中的其他模型。\n2. **处理 CLS Token 差异**：AST 默认使用的 DeiT 模型包含两个 CLS tokens（分类令牌），而大多数其他视觉模型（如标准 ViT）只有一个 CLS token。因此，你必须修改 `forward` 函数，调整 token 的拼接和处理逻辑，以适配单个 CLS token 的情况。\n3. **版本兼容性**：注意 `timm` 库的版本兼容性，原项目基于 `timm==0.4.5` 开发，新版本 API 可能有变动，需相应调整导入和调用方式。",[]]