{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); Note: you can add the theme attribute to the tag to force the theme to be dark or light (by default, it respects the system theme). E.g....3. Write your Gradio app inside of the tagsNow, write your Gradio app as you would normally, in Python! Keep in mind that since this is Python, whitespace and indentations matter. import gradio as grdef greet(name):return \"Hello, \" + name + \"!\"gr.Interface(greet, \"textbox\", \"textbox\").launch()And that's it! You should now be able to open your HTML page in the browser and see the Gradio app rendered! Note that it may take a little while for the Gradio app to load initially since Pyodide can take a while to install in your browser.Note on debugging: to see any errors in your Gradio-lite application, open the inspector in your web browser. All errors (including Python errors) will be printed there.More Examples: Adding Additional Files and RequirementsWhat if you want to create a Gradio app that spans multiple files? Or that has custom Python requirements? Both are possible with @gradio/lite!Multiple FilesAdding multiple files within a @gradio/lite app is very straightforward: use the tag. You can have as many tags as you want, but each one needs to have a name attribute and the entry point to your Gradio app should have the entrypoint attribute.Here's an example:import gradio as grfrom utils import adddemo = gr.Interface(fn=add, inputs=[\"number\", \"number\"], outputs=\"number\")demo.launch()def add(a, b):return a + b\tAdditional RequirementsIf your Gradio app has additional requirements, it is usually possible to install them in the browser using micropip. We've created a wrapper to make this paticularly convenient: simply list your requirements in the same syntax as a requirements.txt and enclose them with tags.Here, we install transformers_js_py to run a text classification model directly in the browser!transformers_js_pyfrom transformers_js import import_transformers_jsimport gradio as grtransformers = await import_transformers_js()pipeline = transformers.pipelinepipe = await pipeline('sentiment-analysis')async def classify(text):return await pipe(text)demo = gr.Interface(classify, \"textbox\", \"json\")demo.launch()\tTry it out: You can see this example running in this Hugging Face Static Space, which lets you host static (serverless) web applications for free. Visit the page and you'll be able to run a machine learning model without internet access!Benefits of Using @gradio/lite1. Serverless DeploymentThe primary advantage of @gradio/lite is that it eliminates the need for server infrastructure. This simplifies deployment, reduces server-related costs, and makes it easier to share your Gradio applications with others.2. Low LatencyBy running in the browser, @gradio/lite offers low-latency interactions for users. There's no need for data to travel to and from a server, resulting in faster responses and a smoother user experience.3. Privacy and SecuritySince all processing occurs within the user's browser, @gradio/lite enhances privacy and security. User data remains on their device, providing peace of mind regarding data handling.LimitationsCurrently, the biggest limitation in using @gradio/lite is that your Gradio apps will generally take more time (usually 5-15 seconds) to load initially in the browser. This is because the browser needs to load the Pyodide runtime before it can render Python code. Not every Python package is supported by Pyodide. While gradio and many other popular packages (including numpy, scikit-learn, and transformers-js) can be installed in Pyodide, if your app has many dependencies, its worth checking whether the dependencies are included in Pyodide, or can be installed with micropip.Try it out!You can immediately try out @gradio/lite by copying and pasting this code in a local index.html file and opening it with your browser:import gradio as grdef greet(name):return \"Hello, \" + name + \"!\"gr.Interface(greet, \"textbox\", \"textbox\").launch()We've also created a playground on the Gradio website that allows you to interactively edit code and see the results immediately! Playground: https://www.gradio.app/playground"}}},{"rowIdx":62,"cells":{"url":{"kind":"string","value":"https://huggingface.co/blog/pytorch-xla"},"targets":{"kind":"string","value":"Hugging Face on PyTorch / XLA TPUs: Faster and cheaper training"},"authors":{"kind":"string","value":"Daniel JinYoung Sohn, Lysandre"},"date":{"kind":"string","value":"February 9, 2021"},"inputs":{"kind":"string","value":"Training Your Favorite Transformers on Cloud TPUs using PyTorch / XLAThe PyTorch-TPU project originated as a collaborative effort between the Facebook PyTorch and Google TPU teams and officially launched at the 2019 PyTorch Developer Conference 2019. Since then, we’ve worked with the Hugging Face team to bring first-class support to training on Cloud TPUs using PyTorch / XLA. This new integration enables PyTorch users to run and scale up their models on Cloud TPUs while maintaining the exact same Hugging Face trainers interface.This blog post provides an overview of changes made in the Hugging Face library, what the PyTorch / XLA library does, an example to get you started training your favorite transformers on Cloud TPUs, and some performance benchmarks. If you can’t wait to get started with TPUs, please skip ahead to the “Train Your Transformer on Cloud TPUs” section - we handle all the PyTorch / XLA mechanics for you within the Trainer module!XLA:TPU Device TypePyTorch / XLA adds a new xla device type to PyTorch. This device type works just like other PyTorch device types. For example, here's how to create and print an XLA tensor:import torchimport torch_xlaimport torch_xla.core.xla_model as xmt = torch.randn(2, 2, device=xm.xla_device())print(t.device)print(t)This code should look familiar. PyTorch / XLA uses the same interface as regular PyTorch with a few additions. Importing torch_xla initializes PyTorch / XLA, and xm.xla_device() returns the current XLA device. This may be a CPU, GPU, or TPU depending on your environment, but for this blog post we’ll focus primarily on TPU.The Trainer module leverages a TrainingArguments dataclass in order to define the training specifics. It handles multiple arguments, from batch sizes, learning rate, gradient accumulation and others, to the devices used. Based on the above, in TrainingArguments._setup_devices() when using XLA:TPU devices, we simply return the TPU device to be used by the Trainer:@dataclassclass TrainingArguments:...@cached_property@torch_requireddef _setup_devices(self) -> Tuple[\"torch.device\", int]:...elif is_torch_tpu_available():device = xm.xla_device()n_gpu = 0...return device, n_gpuXLA Device Step ComputationIn a typical XLA:TPU training scenario we’re training on multiple TPU cores in parallel (a single Cloud TPU device includes 8 TPU cores). So we need to ensure that all the gradients are exchanged between the data parallel replicas by consolidating the gradients and taking an optimizer step. For this we provide the xm.optimizer_step(optimizer) which does the gradient consolidation and step-taking. In the Hugging Face trainer, we correspondingly update the train step to use the PyTorch / XLA APIs:class Trainer:…def train(self, *args, **kwargs):...if is_torch_tpu_available():xm.optimizer_step(self.optimizer)PyTorch / XLA Input PipelineThere are two main parts to running a PyTorch / XLA model: (1) tracing and executing your model’s graph lazily (refer to below “PyTorch / XLA Library” section for a more in-depth explanation) and (2) feeding your model. Without any optimization, the tracing/execution of your model and input feeding would be executed serially, leaving chunks of time during which your host CPU and your TPU accelerators would be idle, respectively. To avoid this, we provide an API, which pipelines the two and thus is able to overlap the tracing of step n+1 while step n is still executing.import torch_xla.distributed.parallel_loader as pl...dataloader = pl.MpDeviceLoader(dataloader, device)Checkpoint Writing and LoadingWhen a tensor is checkpointed from a XLA device and then loaded back from the checkpoint, it will be loaded back to the original device. Before checkpointing tensors in your model, you want to ensure that all of your tensors are on CPU devices instead of XLA devices. This way, when you load back the tensors, you’ll load them through CPU devices and then have the opportunity to place them on whatever XLA devices you desire. We provide the xm.save() API for this, which already takes care of only writing to storage location from only one process on each host (or one globally if using a shared file system across hosts).class PreTrainedModel(nn.Module, ModuleUtilsMixin, GenerationMixin):…def save_pretrained(self, save_directory):...if getattr(self.config, \"xla_device\", False):import torch_xla.core.xla_model as xmif xm.is_master_ordinal():# Save configuration filemodel_to_save.config.save_pretrained(save_directory)# xm.save takes care of saving only from masterxm.save(state_dict, output_model_file)class Trainer:…def train(self, *args, **kwargs):...if is_torch_tpu_available():xm.rendezvous(\"saving_optimizer_states\")xm.save(self.optimizer.state_dict(),os.path.join(output_dir, \"optimizer.pt\"))xm.save(self.lr_scheduler.state_dict(),os.path.join(output_dir, \"scheduler.pt\"))PyTorch / XLA LibraryPyTorch / XLA is a Python package that uses the XLA linear algebra compiler to connect the PyTorch deep learning framework with XLA devices, which includes CPU, GPU, and Cloud TPUs. Part of the following content is also available in our API_GUIDE.md.PyTorch / XLA Tensors are LazyUsing XLA tensors and devices requires changing only a few lines of code. However, even though XLA tensors act a lot like CPU and CUDA tensors, their internals are different. CPU and CUDA tensors launch operations immediately or eagerly. XLA tensors, on the other hand, are lazy. They record operations in a graph until the results are needed. Deferring execution like this lets XLA optimize it. A graph of multiple separate operations might be fused into a single optimized operation.Lazy execution is generally invisible to the caller. PyTorch / XLA automatically constructs the graphs, sends them to XLA devices, and synchronizes when copying data between an XLA device and the CPU. Inserting a barrier when taking an optimizer step explicitly synchronizes the CPU and the XLA device.This means that when you call model(input) forward pass, calculate your loss loss.backward(), and take an optimization step xm.optimizer_step(optimizer), the graph of all operations is being built in the background. Only when you either explicitly evaluate the tensor (ex. Printing the tensor or moving it to a CPU device) or mark a step (this will be done by the MpDeviceLoader everytime you iterate through it), does the full step get executed.Trace, Compile, Execute, and RepeatFrom a user’s point of view, a typical training regimen for a model running on PyTorch / XLA involves running a forward pass, backward pass, and optimizer step. From the PyTorch / XLA library point of view, things look a little different.While a user runs their forward and backward passes, an intermediate representation (IR) graph is traced on the fly. The IR graph leading to each root/output tensor can be inspected as following:>>> import torch>>> import torch_xla>>> import torch_xla.core.xla_model as xm>>> t = torch.tensor(1, device=xm.xla_device())>>> s = t*t>>> print(torch_xla._XLAC._get_xla_tensors_text([s]))IR {%0 = s64[] prim::Constant(), value=1%1 = s64[] prim::Constant(), value=0%2 = s64[] xla::as_strided_view_update(%1, %0), size=(), stride=(), storage_offset=0%3 = s64[] aten::as_strided(%2), size=(), stride=(), storage_offset=0%4 = s64[] aten::mul(%3, %3), ROOT=0}This live graph is accumulated while the forward and backward passes are run on the user's program, and once xm.mark_step() is called (indirectly by pl.MpDeviceLoader), the graph of live tensors is cut. This truncation marks the completion of one step and subsequently we lower the IR graph into XLA Higher Level Operations (HLO), which is the IR language for XLA.This HLO graph then gets compiled into a TPU binary and subsequently executed on the TPU devices. However, this compilation step can be costly, typically taking longer than a single step, so if we were to compile the user’s program every single step, overhead would be high. To avoid this, we have caches that store compiled TPU binaries keyed by their HLO graphs’ unique hash identifiers. So once this TPU binary cache has been populated on the first step, subsequent steps will typically not have to re-compile new TPU binaries; instead, they can simply look up the necessary binaries from the cache.Since TPU compilations are typically much slower than the step execution time, this means that if the graph keeps changing in shape, we’ll have cache misses and compile too frequently. To minimize compilation costs, we recommend keeping tensor shapes static whenever possible. Hugging Face library’s shapes are already static for the most part with input tokens being padded appropriately, so throughout training the cache should be consistently hit. This can be checked using the debugging tools that PyTorch / XLA provides. In the example below, you can see that compilation only happened 5 times (CompileTime) whereas execution happened during each of 1220 steps (ExecuteTime):>>> import torch_xla.debug.metrics as met>>> print(met.metrics_report())Metric: CompileTimeTotalSamples: 5Accumulator: 28s920ms153.731usValueRate: 092ms152.037us / secondRate: 0.0165028 / secondPercentiles: 1%=428ms053.505us; 5%=428ms053.505us; 10%=428ms053.505us; 20%=03s640ms888.060us; 50%=03s650ms126.150us; 80%=11s110ms545.595us; 90%=11s110ms545.595us; 95%=11s110ms545.595us; 99%=11s110ms545.595usMetric: DeviceLockWaitTotalSamples: 1281Accumulator: 38s195ms476.007usValueRate: 151ms051.277us / secondRate: 4.54374 / secondPercentiles: 1%=002.895us; 5%=002.989us; 10%=003.094us; 20%=003.243us; 50%=003.654us; 80%=038ms978.659us; 90%=192ms495.718us; 95%=208ms893.403us; 99%=221ms394.520usMetric: ExecuteTimeTotalSamples: 1220Accumulator: 04m22s555ms668.071usValueRate: 923ms872.877us / secondRate: 4.33049 / secondPercentiles: 1%=045ms041.018us; 5%=213ms379.757us; 10%=215ms434.912us; 20%=217ms036.764us; 50%=219ms206.894us; 80%=222ms335.146us; 90%=227ms592.924us; 95%=231ms814.500us; 99%=239ms691.472usCounter: CachedCompileValue: 1215Counter: CreateCompileHandlesValue: 5...Train Your Transformer on Cloud TPUsTo configure your VM and Cloud TPUs, please follow “Set up a Compute Engine instance” and “Launch a Cloud TPU resource” (pytorch-1.7 version as of writing) sections. Once you have your VM and Cloud TPU created, using them is as simple as SSHing to your GCE VM and running the following commands to get bert-large-uncased training kicked off (batch size is for v3-8 device, may OOM on v2-8):conda activate torch-xla-1.7export TPU_IP_ADDRESS=\"ENTER_YOUR_TPU_IP_ADDRESS\" # ex. 10.0.0.2export XRT_TPU_CONFIG=\"tpu_worker;0;$TPU_IP_ADDRESS:8470\"git clone -b v4.2.2 https://github.com/huggingface/transformers.gitcd transformers && pip install .pip install datasets==1.2.1python examples/xla_spawn.py \\--num_cores 8 \\examples/language-modeling/run_mlm.py \\--dataset_name wikitext \\--dataset_config_name wikitext-103-raw-v1 \\--max_seq_length 512 \\--pad_to_max_length \\--logging_dir ./tensorboard-metrics \\--cache_dir ./cache_dir \\--do_train \\--do_eval \\--overwrite_output_dir \\--output_dir language-modeling \\--overwrite_cache \\--tpu_metrics_debug \\--model_name_or_path bert-large-uncased \\--num_train_epochs 3 \\--per_device_train_batch_size 8 \\--per_device_eval_batch_size 8 \\--save_steps 500000The above should complete training in roughly less than 200 minutes with an eval perplexity of ~3.25.Performance BenchmarkingThe following table shows the performance of training bert-large-uncased on a v3-8 Cloud TPU system (containing 4 TPU v3 chips) running PyTorch / XLA. The dataset used for all benchmarking measurements is the WikiText103 dataset, and we use the run_mlm.py script provided in Hugging Face examples. To ensure that the workloads are not host-CPU-bound, we use the n1-standard-96 CPU configuration for these tests, but you may be able to use smaller configurations as well without impacting performance.NameDatasetHardwareGlobal Batch SizePrecisionTraining Time (mins)bert-large-uncasedWikiText1034 TPUv3 chips (i.e. v3-8)64FP32178.4bert-large-uncasedWikiText1034 TPUv3 chips (i.e. v3-8)128BF16106.4Get Started with PyTorch / XLA on TPUsSee the “Running on TPUs” section under the Hugging Face examples to get started. For a more detailed description of our APIs, check out our API_GUIDE, and for performance best practices, take a look at our TROUBLESHOOTING guide. For generic PyTorch / XLA examples, run the following Colab Notebooks we offer with free Cloud TPU access. To run directly on GCP, please see our tutorials labeled “PyTorch” on our documentation site.Have any other questions or issues? Please open an issue or question at https://github.com/huggingface/transformers/issues or directly at https://github.com/pytorch/xla/issues."}}},{"rowIdx":63,"cells":{"url":{"kind":"string","value":"https://huggingface.co/blog/t2i-sdxl-adapters"},"targets":{"kind":"string","value":"Efficient Controllable Generation for SDXL with T2I-Adapters"},"authors":{"kind":"string","value":"ChongMou, Suraj Patil, Sayak Paul, Xintao Wang, hysts"},"date":{"kind":"string","value":"September 8, 2023"},"inputs":{"kind":"string","value":"T2I-Adapter is an efficient plug-and-play model that provides extra guidance to pre-trained text-to-image models while freezing the original large text-to-image models. T2I-Adapter aligns internal knowledge in T2I models with external control signals. We can train various adapters according to different conditions and achieve rich control and editing effects.As a contemporaneous work, ControlNet has a similar function and is widely used. However, it can be computationally expensive to run. This is because, during each denoising step of the reverse diffusion process, both the ControlNet and UNet need to be run. In addition, ControlNet emphasizes the importance of copying the UNet encoder as a control model, resulting in a larger parameter number. Thus, the generation is bottlenecked by the size of the ControlNet (the larger, the slower the process becomes). T2I-Adapters provide a competitive advantage to ControlNets in this matter. T2I-Adapters are smaller in size, and unlike ControlNets, T2I-Adapters are run just once for the entire course of the denoising process. Model TypeModel ParametersStorage (fp16)ControlNet-SDXL1251 M2.5 GBControlLoRA (with rank 128)197.78 M (84.19% reduction)396 MB (84.53% reduction)T2I-Adapter-SDXL79 M (93.69% reduction)158 MB (94% reduction)Over the past few weeks, the Diffusers team and the T2I-Adapter authors have been collaborating to bring the support of T2I-Adapters for Stable Diffusion XL (SDXL) in diffusers. In this blog post, we share our findings from training T2I-Adapters on SDXL from scratch, some appealing results, and, of course, the T2I-Adapter checkpoints on various conditionings (sketch, canny, lineart, depth, and openpose)!Compared to previous versions of T2I-Adapter (SD-1.4/1.5), T2I-Adapter-SDXL still uses the original recipe, driving 2.6B SDXL with a 79M Adapter! T2I-Adapter-SDXL maintains powerful control capabilities while inheriting the high-quality generation of SDXL!Training T2I-Adapter-SDXL with diffusersWe built our training script on this official example provided by diffusers. Most of the T2I-Adapter models we mention in this blog post were trained on 3M high-resolution image-text pairs from LAION-Aesthetics V2 with the following settings: Training steps: 20000-35000Batch size: Data parallel with a single GPU batch size of 16 for a total batch size of 128.Learning rate: Constant learning rate of 1e-5.Mixed precision: fp16We encourage the community to use our scripts to train custom and powerful T2I-Adapters, striking a competitive trade-off between speed, memory, and quality. Using T2I-Adapter-SDXL in diffusersHere, we take the lineart condition as an example to demonstrate the usage of T2I-Adapter-SDXL. To get started, first install the required dependencies:pip install -U git+https://github.com/huggingface/diffusers.gitpip install -U controlnet_aux==0.0.7 # for conditioning models and detectorspip install transformers accelerate The generation process of the T2I-Adapter-SDXL mainly consists of the following two steps:Condition images are first prepared into the appropriate control image format.The control image and prompt are passed to the StableDiffusionXLAdapterPipeline.Let's have a look at a simple example using the Lineart Adapter. We start by initializing the T2I-Adapter pipeline for SDXL and the lineart detector. import torchfrom controlnet_aux.lineart import LineartDetectorfrom diffusers import (AutoencoderKL, EulerAncestralDiscreteScheduler,StableDiffusionXLAdapterPipeline, T2IAdapter)from diffusers.utils import load_image, make_image_grid# load adapteradapter = T2IAdapter.from_pretrained(\"TencentARC/t2i-adapter-lineart-sdxl-1.0\", torch_dtype=torch.float16, varient=\"fp16\").to(\"cuda\")# load pipelinemodel_id = \"stabilityai/stable-diffusion-xl-base-1.0\"euler_a = EulerAncestralDiscreteScheduler.from_pretrained(model_id, subfolder=\"scheduler\")vae = AutoencoderKL.from_pretrained(\"madebyollin/sdxl-vae-fp16-fix\", torch_dtype=torch.float16)pipe = StableDiffusionXLAdapterPipeline.from_pretrained(model_id,vae=vae,adapter=adapter,scheduler=euler_a,torch_dtype=torch.float16,variant=\"fp16\",).to(\"cuda\")# load lineart detectorline_detector = LineartDetector.from_pretrained(\"lllyasviel/Annotators\").to(\"cuda\")Then, load an image to detect lineart:url = \"https://huggingface.co/Adapter/t2iadapter/resolve/main/figs_SDXLV1.0/org_lin.jpg\"image = load_image(url)image = line_detector(image, detect_resolution=384, image_resolution=1024)Then we generate: prompt = \"Ice dragon roar, 4k photo\"negative_prompt = \"anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured\"gen_images = pipe(prompt=prompt,negative_prompt=negative_prompt,image=image,num_inference_steps=30,adapter_conditioning_scale=0.8,guidance_scale=7.5,).images[0]gen_images.save(\"out_lin.png\")There are two important arguments to understand that help you control the amount of conditioning.adapter_conditioning_scaleThis argument controls how much influence the conditioning should have on the input. High values mean a higher conditioning effect and vice-versa. adapter_conditioning_factorThis argument controls how many initial generation steps should have the conditioning applied. The value should be set between 0-1 (default is 1). The value of adapter_conditioning_factor=1 means the adapter should be applied to all timesteps, while the adapter_conditioning_factor=0.5 means it will only applied for the first 50% of the steps.For more details, we welcome you to check the official documentation. Try out the DemoYou can easily try T2I-Adapter-SDXL in this Space or in the playground embedded below:You can also try out Doodly, built using the sketch model that turns your doodles into realistic images (with language supervision):More ResultsBelow, we present results obtained from using different kinds of conditions. We also supplement the results with links to their corresponding pre-trained checkpoints. Their model cards contain more details on how they were trained, along with example usage. Lineart GuidedModel from TencentARC/t2i-adapter-lineart-sdxl-1.0Sketch GuidedModel from TencentARC/t2i-adapter-sketch-sdxl-1.0Canny GuidedModel from TencentARC/t2i-adapter-canny-sdxl-1.0Depth GuidedDepth guided models from TencentARC/t2i-adapter-depth-midas-sdxl-1.0 and TencentARC/t2i-adapter-depth-zoe-sdxl-1.0 respectivelyOpenPose GuidedModel from TencentARC/t2i-adapter-openpose-sdxl-1.0Acknowledgements: Immense thanks to William Berman for helping us train the models and sharing his insights."}}},{"rowIdx":64,"cells":{"url":{"kind":"string","value":"https://huggingface.co/blog/mask2former"},"targets":{"kind":"string","value":"Universal Image Segmentation with Mask2Former and OneFormer"},"authors":{"kind":"string","value":"Niels Rogge, Shivalika Singh, Alara Dirik"},"date":{"kind":"string","value":"January 19, 2023"},"inputs":{"kind":"string","value":"This guide introduces Mask2Former and OneFormer, 2 state-of-the-art neural networks for image segmentation. The models are now available in 🤗 transformers, an open-source library that offers easy-to-use implementations of state-of-the-art models. Along the way, you'll learn about the difference between the various forms of image segmentation.\t\tImage segmentation\tImage segmentation is the task of identifying different \"segments\" in an image, like people or cars. More technically, image segmentation is the task of grouping pixels with different semantics. Refer to the Hugging Face task page for a brief introduction.Image segmentation can largely be split into 3 subtasks - instance, semantic and panoptic segmentation - with numerous methods and model architectures to perform each subtask.instance segmentation is the task of identifying different \"instances\", like individual people, in an image. Instance segmentation is very similar to object detection, except that we'd like to output a set of binary segmentation masks, rather than bounding boxes, with corresponding class labels. Instances are oftentimes also called \"objects\" or \"things\". Note that individual instances may overlap.semantic segmentation is the task of identifying different \"semantic categories\", like \"person\" or \"sky\" of each pixel in an image. Contrary to instance segmentation, no distinction is made between individual instances of a given semantic category; one just likes to come up with a mask for the \"person\" category, rather than for the individual people for example. Semantic categories which don't have individual instances, like \"sky\" or \"grass\", are oftentimes referred to as \"stuff\", to make the distinction with \"things\" (great names, huh?). Note that no overlap between semantic categories is possible, as each pixel belongs to one category.panoptic segmentation, introduced in 2018 by Kirillov et al., aims to unify instance and semantic segmentation, by making models simply identify a set of \"segments\", each with a corresponding binary mask and class label. Segments can be both \"things\" or \"stuff\". Unlike in instance segmentation, no overlap between different segments is possible.The figure below illustrates the difference between the 3 subtasks (taken from this blog post).Over the last years, researchers have come up with several architectures that were typically very tailored to either instance, semantic or panoptic segmentation. Instance and panoptic segmentation were typically solved by outputting a set of binary masks + corresponding labels per object instance (very similar to object detection, except that one outputs a binary mask instead of a bounding box per instance). This is oftentimes called \"binary mask classification\". Semantic segmentation on the other hand was typically solved by making models output a single \"segmentation map\" with one label per pixel. Hence, semantic segmentation was treated as a \"per-pixel classification\" problem. Popular semantic segmentation models which adopt this paradigm are SegFormer, on which we wrote an extensive blog post, and UPerNet.\t\tUniversal image segmentation\tLuckily, since around 2020, people started to come up with models that can solve all 3 tasks (instance, semantic and panoptic segmentation) with a unified architecture, using the same paradigm. This started with DETR, which was the first model that solved panoptic segmentation using a \"binary mask classification\" paradigm, by treating \"things\" and \"stuff\" classes in a unified way. The key innovation was to have a Transformer decoder come up with a set of binary masks + classes in a parallel way. This was then improved in the MaskFormer paper, which showed that the \"binary mask classification\" paradigm also works really well for semantic segmentation.Mask2Former extends this to instance segmentation by further improving the neural network architecture. Hence, we've evolved from separate architectures to what researchers now refer to as \"universal image segmentation\" architectures, capable of solving any image segmentation task. Interestingly, these universal models all adopt the \"mask classification\" paradigm, discarding the \"per-pixel classification\" paradigm entirely. A figure illustrating Mask2Former's architecture is depicted below (taken from the original paper).In short, an image is first sent through a backbone (which, in the paper could be either ResNet or Swin Transformer) to get a list of low-resolution feature maps. Next, these feature maps are enhanced using a pixel decoder module to get high-resolution features. Finally, a Transformer decoder takes in a set of queries and transforms them into a set of binary mask and class predictions, conditioned on the pixel decoder's features.Note that Mask2Former still needs to be trained on each task separately to obtain state-of-the-art results. This has been improved by the OneFormer model, which obtains state-of-the-art performance on all 3 tasks by only training on a panoptic version of the dataset (!), by adding a text encoder to condition the model on either \"instance\", \"semantic\" or \"panoptic\" inputs. This model is also as of today available in 🤗 transformers. It's even more accurate than Mask2Former, but comes with greater latency due to the additional text encoder. See the figure below for an overview of OneFormer. It leverages either Swin Transformer or the new DiNAT model as backbone.\t\tInference with Mask2Former and OneFormer in Transformers\tUsage of Mask2Former and OneFormer is pretty straightforward, and very similar to their predecessor MaskFormer. Let's instantiate a Mask2Former model from the hub trained on the COCO panoptic dataset, along with its processor. Note that the authors released no less than 30 checkpoints trained on various datasets.from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentationprocessor = AutoImageProcessor.from_pretrained(\"facebook/mask2former-swin-base-coco-panoptic\")model = Mask2FormerForUniversalSegmentation.from_pretrained(\"facebook/mask2former-swin-base-coco-panoptic\")Next, let's load the familiar cats image from the COCO dataset, on which we'll perform inference.from PIL import Imageurl = \"http://images.cocodataset.org/val2017/000000039769.jpg\"image = Image.open(requests.get(url, stream=True).raw)imageWe prepare the image for the model using the image processor, and forward it through the model.inputs = processor(image, return_tensors=\"pt\")with torch.no_grad(): outputs = model(**inputs)The model outputs a set of binary masks and corresponding class logits. The raw outputs of Mask2Former can be easily postprocessed using the image processor to get the final instance, semantic or panoptic segmentation predictions:prediction = processor.post_process_panoptic_segmentation(outputs, target_sizes=[image.size[::-1]])[0]print(prediction.keys())Output:----------------------------------------------------------------------------------------------------dict_keys(['segmentation', 'segments_info'])In panoptic segmentation, the final prediction contains 2 things: a segmentation map of shape (height, width) where each value encodes the instance ID of a given pixel, as well as a corresponding segments_info. The segments_info contains more information about the individual segments of the map (such as their class / category ID). Note that Mask2Former outputs binary mask proposals of shape (96, 96) for efficiency and the target_sizes argument is used to resize the final mask to the original image size.Let's visualize the results:from collections import defaultdictimport matplotlib.pyplot as pltimport matplotlib.patches as mpatchesfrom matplotlib import cmdef draw_panoptic_segmentation(segmentation, segments_info): # get the used color map viridis = cm.get_cmap('viridis', torch.max(segmentation)) fig, ax = plt.subplots() ax.imshow(segmentation) instances_counter = defaultdict(int) handles = [] # for each segment, draw its legend for segment in segments_info: segment_id = segment['id'] segment_label_id = segment['label_id'] segment_label = model.config.id2label[segment_label_id] label = f\"{segment_label}-{instances_counter[segment_label_id]}\" instances_counter[segment_label_id] += 1 color = viridis(segment_id) handles.append(mpatches.Patch(color=color, label=label)) ax.legend(handles=handles)draw_panoptic_segmentation(**panoptic_segmentation)Here, we can see that the model is capable of detecting the individual cats and remotes in the image. Semantic segmentation on the other hand would just create a single mask for the \"cat\" category.To perform inference with OneFormer, which has an identical API except that it also takes an additional text prompt as input, we refer to the demo notebook.\t\tFine-tuning Mask2Former and OneFormer in Transformers\tFor fine-tuning Mask2Former/OneFormer on a custom dataset for either instance, semantic and panoptic segmentation, check out our demo notebooks. MaskFormer, Mask2Former and OneFormer share a similar API so upgrading from MaskFormer is easy and requires minimal changes.The demo notebooks make use of MaskFormerForInstanceSegmentation to load the model whereas you'll have to switch to using either Mask2FormerForUniversalSegmentation or OneFormerForUniversalSegmentation. In case of image processing for Mask2Former, you'll also have to switch to using Mask2FormerImageProcessor. You can also load the image processor using the AutoImageProcessor class which automatically takes care of loading the correct processor corresponding to your model. OneFormer on the other hand requires a OneFormerProcessor, which prepares the images, along with a text input, for the model.\t\tConclusion\tThat's it! You now know about the difference between instance, semantic and panoptic segmentation, as well as how to use \"universal architectures\" such as Mask2Former and OneFormer using the 🤗 transformers library.We hope you enjoyed this post and learned something. Feel free to let us know whether you are satisfied with the results when fine-tuning Mask2Former or OneFormer.If you liked this topic and want to learn more, we recommend the following resources:Our demo notebooks for MaskFormer, Mask2Former and OneFormer, which give a broader overview on inference (including visualization) as well as fine-tuning on custom data.The [live demo spaces] for Mask2Former and OneFormer available on the Hugging Face Hub which you can use to quickly try out the models on sample inputs of your choice."}}},{"rowIdx":65,"cells":{"url":{"kind":"string","value":"https://huggingface.co/blog/open-llm-leaderboard-drop"},"targets":{"kind":"string","value":"Open LLM Leaderboard: DROP deep dive"},"authors":{"kind":"string","value":"Clémentine Fourrier, Alex Cabrera, Stella Biderman, Nathan Habib, Thomas Wolf"},"date":{"kind":"string","value":"December 1, 2023"},"inputs":{"kind":"string","value":"Recently, three new benchmarks were added to the Open LLM Leaderboard: Winogrande, GSM8k and DROP, using the original implementations reproduced in the EleutherAI Harness. A cursory look at the scores for DROP revealed something strange was going on, with the overwhelming majority of models scoring less than 10 out of 100 on their f1-score! We did a deep dive to understand what was going on, come with us to see what we found out!Initial observationsDROP (Discrete Reasoning Over Paragraphs) is an evaluation where models must extract relevant information from English-text paragraphs before executing discrete reasoning steps on them (for example, sorting or counting items to arrive at the correct answer, see the table below for examples). The metrics used are custom f1 and exact match scores.Examples of reasoning and paragraph from the original article.We added it to the Open LLM Leaderboard three weeks ago, and observed that the f1-scores of pretrained models followed an unexpected trend: when we plotted DROP scores against the leaderboard original average (of ARC, HellaSwag, TruthfulQA and MMLU), which is a reasonable proxy for overall model performance, we expected DROP scores to be correlated with it (with better models having better performance). However, this was only the case for a small number of models, and all the others had a very low DROP f1-score, below 10.Two trends can be observed in the DROP scores: some follow the average (in diagonal), others are stuck around 5 (vertical line on the right of the graph).Normalization interrogationsDuring our first deeper dive in these surprising behavior, we observed that the normalization step was possibly not working as intended: in some cases, this normalization ignored the correct numerical answers when they were directly followed by a whitespace character other than a space (a line return, for example).Let's look at an example, with the generation being 10Passage: The 2011 census recorded a population of 1,001,360, and the gold answer being 10.Normalization happens in several steps, both for generation and gold:Split on separators |, -, or The beginning sequence of the generation 10Passage: contain no such separator, and is therefore considered a single entity after this step.Punctuation removalThe first token then becomes 10Passage (: is removed)Homogenization of numbers Every string that can be cast to float is considered a number and cast to float, then re-converted to string. 10Passage stays the same, as it cannot be cast to float, whereas the gold 10 becomes 10.0.Other stepsA lot of other normalization steps ensue (removing articles, removing other whitespaces, etc.) and our original example becomes 10 passage 2011.0 census recorded population of 1001360.0.However, the overall score is not computed on the string, but on the bag of words (BOW) extracted from the string, here {'recorded', 'population', 'passage', 'census', '2011.0', '1001360.0', '10'}, which is compared with the BOW of the gold, also normalized in the above manner, {10.0}. As you can see, they don’t intersect, even though the model predicted the correct output!In summary, if a number is followed by any kind of whitespace other than a simple space, it will not pass through the number normalization, hence never match the gold if it is also a number! This first issue was likely to mess up the scores quite a bit, but clearly it was not the only factor causing DROP scores to be so low. We decided to investigate a bit more.Diving into the resultsExtending our investigations, our friends at Zeno joined us and undertook a much more thorough exploration of the results, looking at 5 models which were representative of the problems we noticed in DROP scores: falcon-180B and mistral-7B were underperforming compared to what we were expecting, Yi-34B and tigerbot-70B had a very good performance on DROP correlated with their average scores, and facebook/xglm-7.5B fell in the middle. You can give analyzing the results a try in the Zeno project here if you want to!The Zeno team found two even more concerning features:Not a single model got a correct result on floating point answersHigh quality models which generate long answers actually have a lower f1-scoreAt this point, we believed that both failure cases were actually caused by the same root factor: using . as a stopword token (to end the generations):Floating point answers are systematically interrupted before their generation is completeHigher quality models, which try to match the few-shot prompt format, will generate AnswerPlausible prompt for the next question., and only stop during the plausible prompt continuation after the actual answer on the first ., therefore generating too many words and getting a bad f1 score.We hypothesized that both these problems could be fixed by using instead of . as an end of generation stop word.Changing the end of generation tokenSo we gave it a try! We investigated using as the end of generation token on the available results. We split the generated answer on the first it contained, if one was present, and recomputed the scores. Note that this is only an approximation of the correct result, as it won't fix answers that were cut too early on . (for example floating point answers) - but it also won’t give unfair advantage to any model, as all of them were affected by this problem. However it’s the best we could do without rerunning models (as we wanted to keep the community posted as soon as possible).The results we got were the following - splitting on correlates really well with other scores and therefore with overall performance. We can see in orange that the scores computed on the new strings correlate much better with the average performance.So what's next?A quick calculation shows that re-running the full evaluation of all models would be quite costly (the full update took 8 years of GPU time, and a lot of it was taken by DROP), we estimated how much it would cost to only re-run failing examples.In 10% of the cases, the gold answer is a floating number (for example 12.25) and model predictions start with the correct beginning (for our example, 12) but are cut off on a . - these predictions likely would have actually been correct if the generation was to continue. We would definitely need to re-run them!Our estimation does not count generated sentences that finish with a number which was possibly interrupted (40% of the other generations), nor any prediction messed up by its normalization.To get correct results, we would thus need to re-run more than 50% of the examples, a huge amount of GPU time! We need to be certain that the implementation we'll run is correct this time.After discussing it with the fantastic EleutherAI team (both on GitHub and internally), who guided us through the code and helped our investigations, it became very clear that the LM Eval Harness implementation follows the \"official DROP\" code very strictly: a new version of this benchmark’s evaluation thus needs to be developed! We have therefore taken the decision to remove DROP from the Open LLM Leaderboard until a new version arises.One take away of this investiguation is the value in having the many eyes of the community collaboratively investiguate a benchmark in order to detect errors that were previously missed. Here again the power of open-source, community and developping in the open-shines in that it allows to transparently investigate the root cause of an issue on a benchmark which has been out there for a couple of years. We hope that interested members of the community will join forces with academics working on DROP evaluation to fix both its scoring and its normalization. We'd love it becomes usable again, as the dataset itself is really quite interesting and cool. We encourage you to provide feedback on how we should evaluate DROP on this issue.Thanks to the many community members who pointed out issues on DROP scores, and many thanks to the EleutherAI Harness and Zeno teams for their great help on this issue."}}},{"rowIdx":66,"cells":{"url":{"kind":"string","value":"https://huggingface.co/blog/unity-in-spaces"},"targets":{"kind":"string","value":"How to host a Unity game in a Space"},"authors":{"kind":"string","value":"Dylan Ebert"},"date":{"kind":"string","value":"April 21, 2023"},"inputs":{"kind":"string","value":"Did you know you can host a Unity game in a Hugging Face Space? No? Well, you can!Hugging Face Spaces are an easy way to build, host, and share demos. While they are typically used for Machine Learning demos, they can also host playable Unity games. Here are some examples:HuggyFarming Game Unity API DemoHere's how you can host your own Unity game in a Space.Step 1: Create a Space using the Static HTML templateFirst, navigate to Hugging Face Spaces to create a space.Select the \"Static HTML\" template, give your Space a name, and create it.Step 2: Use Git to Clone the SpaceClone your newly created Space to your local machine using Git. You can do this by running the following command in your terminal or command prompt:git clone https://huggingface.co/spaces/{your-username}/{your-space-name}Step 3: Open your Unity ProjectOpen the Unity project you want to host in your Space.Step 4: Switch the Build Target to WebGLNavigate to File > Build Settings and switch the Build Target to WebGL.Step 5: Open Player SettingsIn the Build Settings window, click the \"Player Settings\" button to open the Player Settings panel.Step 6: Optionally, Download the Hugging Face Unity WebGL TemplateYou can enhance your game's appearance in a Space by downloading the Hugging Face Unity WebGL template, available here. Just download the repository and drop it in your project files.Then, in the Player Settings panel, switch the WebGL template to Hugging Face. To do so, in Player Settings, click \"Resolution and Presentation\", then select the Hugging Face WebGL template.Step 7: Change the Compression Format to DisabledIn the Player Settings panel, navigate to the \"Publishing Settings\" section and change the Compression Format to \"Disabled\".Step 8: Build your ProjectReturn to the Build Settings window and click the \"Build\" button. Choose a location to save your build files, and Unity will build the project for WebGL.Step 9: Copy the Contents of the Build FolderAfter the build process is finished, navigate to the folder containing your build files. Copy the files in the build folder to the repository you cloned in Step 2.Step 10: Enable Git-LFS for Large File StorageNavigate to your repository. Use the following commands to track large build files.git lfs installgit lfs track Build/* Step 11: Push your ChangesFinally, use the following Git commands to push your changes:git add .git commit -m \"Add Unity WebGL build files\"git pushDone!Congratulations! Refresh your Space. You should now be able to play your game in a Hugging Face Space.We hope you found this tutorial helpful. If you have any questions or would like to get more involved in using Hugging Face for Games, join the Hugging Face Discord!"}}},{"rowIdx":67,"cells":{"url":{"kind":"string","value":"https://huggingface.co/blog/gaussian-splatting"},"targets":{"kind":"string","value":"Introduction to 3D Gaussian Splatting"},"authors":{"kind":"string","value":"Dylan Ebert"},"date":{"kind":"string","value":"September 18, 2023"},"inputs":{"kind":"string","value":"3D Gaussian Splatting is a rasterization technique described in 3D Gaussian Splatting for Real-Time Radiance Field Rendering that allows real-time rendering of photorealistic scenes learned from small samples of images. This article will break down how it works and what it means for the future of graphics.\t\tWhat is 3D Gaussian Splatting?\t3D Gaussian Splatting is, at its core, a rasterization technique. That means:Have data describing the scene.Draw the data on the screen.This is analogous to triangle rasterization in computer graphics, which is used to draw many triangles on the screen.However, instead of triangles, it's gaussians. Here's a single rasterized gaussian, with a border drawn for clarity.It's described by the following parameters:Position: where it's located (XYZ)Covariance: how it's stretched/scaled (3x3 matrix)Color: what color it is (RGB)Alpha: how transparent it is (α)In practice, multiple gaussians are drawn at once.That's three gaussians. Now what about 7 million gaussians?Here's what it looks like with each gaussian rasterized fully opaque:That's a very brief overview of what 3D Gaussian Splatting is. Next, let's walk through the full procedure described in the paper.\t\tHow it works\t\t\t1. Structure from Motion\tThe first step is to use the Structure from Motion (SfM) method to estimate a point cloud from a set of images. This is a method for estimating a 3D point cloud from a set of 2D images. This can be done with the COLMAP library.\t\t2. Convert to Gaussians\tNext, each point is converted to a gaussian. This is already sufficient for rasterization. However, only position and color can be inferred from the SfM data. To learn a representation that yields high quality results, we need to train it.\t\t3. Training\tThe training procedure uses Stochastic Gradient Descent, similar to a neural network, but without the layers. The training steps are:Rasterize the gaussians to an image using differentiable gaussian rasterization (more on that later)Calculate the loss based on the difference between the rasterized image and ground truth imageAdjust the gaussian parameters according to the lossApply automated densification and pruningSteps 1-3 are conceptually pretty straightforward. Step 4 involves the following:If the gradient is large for a given gaussian (i.e. it's too wrong), split/clone itIf the gaussian is small, clone itIf the gaussian is large, split itIf the alpha of a gaussian gets too low, remove itThis procedure helps the gaussians better fit fine-grained details, while pruning unnecessary gaussians.\t\t4. Differentiable Gaussian Rasterization\tAs mentioned earlier, 3D Gaussian Splatting is a rasterization approach, which draws the data to the screen. However, some important elements are also that it's:FastDifferentiableThe original implementation of the rasterizer can be found here. The rasterization involves:Project each gaussian into 2D from the camera perspective.Sort the gaussians by depth.For each pixel, iterate over each gaussian front-to-back, blending them together.Additional optimizations are described in the paper.It's also essential that the rasterizer is differentiable, so that it can be trained with stochastic gradient descent. However, this is only relevant for training - the trained gaussians can also be rendered with a non-differentiable approach.\t\tWho cares?\tWhy has there been so much attention on 3D Gaussian Splatting? The obvious answer is that the results speak for themselves - it's high-quality scenes in real-time. However, there may be more to the story.There are many unknowns as to what else can be done with Gaussian Splatting. Can they be animated? The upcoming paper Dynamic 3D Gaussians: tracking by Persistent Dynamic View Synthesis suggests that they can. There are many other unknowns as well. Can they do reflections? Can they be modeled without training on reference images?Finally, there is growing research interest in Embodied AI. This is an area of AI research where state-of-the-art performance is still orders of magnitude below human performance, with much of the challenge being in representing 3D space. Given that 3D Gaussian Splatting yields a very dense representation of 3D space, what might the implications be for Embodied AI research?These questions call attention to the method. It remains to be seen what the actual impact will be.\t\tThe future of graphics\tSo what does this mean for the future of graphics? Well, let's break it up into pros/cons:ProsHigh-quality, photorealistic scenesFast, real-time rasterizationRelatively fast to trainConsHigh VRAM usage (4GB to view, 12GB to train)Large disk size (1GB+ for a scene)Incompatible with existing rendering pipelinesStatic (for now)So far, the original CUDA implementation has not been adapted to production rendering pipelines, like Vulkan, DirectX, WebGPU, etc, so it's yet to be seen what the impact will be.There have already been the following adaptations:Remote viewerWebGPU viewerWebGL viewerUnity viewerOptimized WebGL viewerThese rely either on remote streaming (1) or a traditional quad-based rasterization approach (2-5). While a quad-based approach is compatible with decades of graphics technologies, it may result in lower quality/performance. However, viewer #5 demonstrates that optimization tricks can result in high quality/performance, despite a quad-based approach.So will we see 3D Gaussian Splatting fully reimplemented in a production environment? The answer is probably yes. The primary bottleneck is sorting millions of gaussians, which is done efficiently in the original implementation using CUB device radix sort, a highly optimized sort only available in CUDA. However, with enough effort, it's certainly possible to achieve this level of performance in other rendering pipelines.If you have any questions or would like to get involved, join the Hugging Face Discord!"}}},{"rowIdx":68,"cells":{"url":{"kind":"string","value":"https://huggingface.co/blog/researcher-dataset-sharing"},"targets":{"kind":"string","value":"Creating open machine learning datasets? Share them on the Hugging Face Hub!"},"authors":{"kind":"string","value":"Daniel van Strien"},"date":{"kind":"string","value":"October 30, 2023"},"inputs":{"kind":"string","value":"Who is this blog post for?Are you a researcher doing data-intensive research or using machine learning as a research tool? As part of this research, you have likely created datasets for training and evaluating machine learning models, and like many researchers, you may be sharing these datasets via Google Drive, OneDrive, or your own personal server. In this post, we’ll outline why you might want to consider sharing these datasets on the Hugging Face Hub instead. This post outlines:Why researchers should openly share their data (feel free to skip this section if you are already convinced about this!)What the Hugging Face Hub offers for researchers who want to share their datasets.Resources for getting started with sharing your datasets on the Hugging Face Hub.Why share your data?Machine learning is increasingly utilized across various disciplines, enhancing research efficiency in tackling diverse problems. Data remains crucial for training and evaluating models, especially when developing new machine-learning methods for specific tasks or domains. Large Language Models may not perform well on specialized tasks like bio-medical entity extraction, and computer vision models might struggle with classifying domain specific images.Domain-specific datasets are vital for evaluating and training machine learning models, helping to overcome the limitations of existing models. Creating these datasets, however, is challenging, requiring significant time, resources, and domain expertise, particularly for annotating data. Maximizing the impact of this data is crucial for the benefit of both the researchers involved and their respective fields.The Hugging Face Hub can help achieve this maximum impact. What is the Hugging Face Hub?The Hugging Face Hub has become the central hub for sharing open machine learning models, datasets and demos, hosting over 360,000 models and 70,000 datasets. The Hub enables people – including researchers – to access state-of-the-art machine learning models and datasets in a few lines of code. Datasets on the Hugging Face Hub.What does the Hugging Face Hub offer for data sharing?This blog post won’t cover all of the features and benefits of hosting datasets on the Hugging Face Hub but will instead highlight some that are particularly relevant for researchers. Visibility for your workThe Hugging Face Hub has become the central Hub for people to collaborate on open machine learning. Making your datasets available via the Hugging Face Hub ensures it is visible to a wide audience of machine learning researchers. The Hub makes it possible to expose links between datasets, models and demos which makes it easier to see how people are using your datasets for training models and creating demos. Tools for exploring and working with datasetsThere are a growing number of tools being created which make it easier to understand datasets hosted on the Hugging Face Hub. Tools for loading datasets hosted on the Hugging Face HubDatasets shared on the Hugging Face Hub can be loaded via a variety of tools. The datasets library is a Python library which can directly load datasets from the huggingface hub via a load_dataset command. The datasets library is optimized for working with large datasets (including datasets which won't fit into memory) and supporting machine learning workflows. Alongside this many of the datasets on the Hub can also be loaded directly into Pandas, Polars, and DuckDB. This page provides a more detailed overview of the different ways you can load datasets from the Hub.Datasets ViewerThe datasets viewer allows people to explore and interact with datasets hosted on the Hub directly in the browser by visiting the dataset repository on the Hugging Face Hub. This makes it much easier for others to view and explore your data without first having to download it. The datasets viewer also allows you to search and filter datasets, which can be valuable to potential dataset users, understanding the nature of a dataset more quickly.The dataset viewer for the multiconer_v2 Named Entity Recognition dataset.Community toolsAlongside the datasets viewer there are a growing number of community created tools for exploring datasets on the Hub.SpotlightSpotlight is a tool that allows you to interactively explore datasets on the Hub with one line of code. You can learn more about how you can use this tool in this blog post.LilacLilac is a tool that aims to help you \"curate better data for LLMs\" and allows you to explore natural language datasets more easily. The tool allows you to semantically search your dataset (search by meaning), cluster data and gain high-level insights into your dataset.A Spaces demo of the lilac tool.You can explore the Lilac tool further in a demo.This growing number of tools for exploring datasets on the Hub makes it easier for people to explore and understand your datasets and can help promote your datasets to a wider audience.Support for large datasetsThe Hub can host large datasets; it currently hosts datasets with multiple TBs of data.The datasets library, which users can use to download and process datasets from the Hub, supports streaming, making it possible to work with large datasets without downloading the entire dataset upfront. This can be invaluable for allowing researchers with less computational resources to work with your datasets, or to select small portions of a huge dataset for testing, development or prototyping.The Hugging Face Hub can host the large datasets often created for machine learning research.API and client library interaction with the HubInteracting with the Hugging Face Hub via an API or the huggingface_hub Python library is possible. This includes creating new repositories, uploading data programmatically and creating and modifying metadata for datasets. This can be powerful for research workflows where new data or annotations continue to be created. The client library also makes uploading large datasets much more accessible. CommunityThe Hugging Face Hub is already home to a large community of researchers, developers, artists, and others interested in using and contributing to an ecosystem of open-source machine learning. Making your datasets accessible to this community increases their visibility, opens them up to new types of users and places your datasets within the context of a larger ecosystem of models, datasets and libraries.The Hub also has features which allow communities to collaborate more easily. This includes a discussion page for each dataset, model and Space hosted on the Hub. This means users of your datasets can quickly ask questions and discuss ideas for working with a dataset. The Hub makes it easy to ask questions and discuss datasets.Other important features for researchersSome other features of the Hub may be of particular interest to researchers wanting to share their machine learning datasets on the Hub:Organizations allow you to collaborate with other people and share models, datasets and demos under a single organization. This can be an excellent way of highlighting the work of a particular research project or institute. Gated repositories allow you to add some access restrictions to accessing your dataset. Download metrics are available for datasets on the Hub; this can be useful for communicating the impact of your researchers to funders and hiring committees. Digital Object Identifiers (DOI): it’s possible to register a persistent identifier for your dataset.How can I share my dataset on the Hugging Face Hub?Here are some resources to help you get started with sharing your datasets on the Hugging Face Hub:General guidance on creating and sharing datasets on the HubGuides for particular modalities:Creating an audio datasetCreating an image datasetGuidance on structuring your repository so a dataset can be automatically loaded from the Hub.The following pages will be useful if you want to share large datasets:Repository limitations and recommendations provides general guidance on some of the considerations you'll want to make when sharing large datasets.The Tips and tricks for large uploads page provides some guidance on how to upload large datasets to the Hub.If you want any further help uploading a dataset to the Hub or want to upload a particularly large dataset, please contact datasets@huggingface.co."}}},{"rowIdx":69,"cells":{"url":{"kind":"string","value":"https://huggingface.co/blog/cnil"},"targets":{"kind":"string","value":"Hugging Face Selected for the French Data Protection Agency Enhanced Support Program"},"authors":{"kind":"string","value":"Yacine Jernite, Julien Chaumond, Anna Tordjmann, Ima Bello"},"date":{"kind":"string","value":"May 15, 2023"},"inputs":{"kind":"string","value":"Hugging Face Selected for the French Data Protection Agency Enhanced Support ProgramHugging FaceModelsDatasetsSpacesPostsDocsSolutionsPricingLog InSign UpBack to ArticlesHugging Face Selected for the French Data Protection Agency Enhanced Support Program"}}},{"rowIdx":70,"cells":{"url":{"kind":"string","value":"https://huggingface.co/blog/fhe-endpoints"},"targets":{"kind":"string","value":"Running Privacy-Preserving Inferences on Hugging Face Endpoints"},"authors":{"kind":"string","value":"Benoit Chevallier-Mames"},"date":{"kind":"string","value":"April 16, 2024"},"inputs":{"kind":"string","value":"This is a guest blog post by the Zama team. Zama is an open source cryptography company building state-of-the-art FHE solutions for blockchain and AI.Eighteen months ago, Zama started Concrete ML, a privacy-preserving ML framework with bindings to traditional ML frameworks such as scikit-learn, ONNX, PyTorch, and TensorFlow. To ensure privacy for users' data, Zama uses Fully Homomorphic Encryption (FHE), a cryptographic tool that allows to make direct computations over encrypted data, without ever knowing the private key.From the start, we wanted to pre-compile some FHE-friendly networks and make them available somewhere on the internet, allowing users to use them trivially. We are ready today! And not in a random place on the internet, but directly on Hugging Face.More precisely, we use Hugging Face Endpoints and custom inference handlers, to be able to store our Concrete ML models and let users deploy on HF machines in one click. At the end of this blog post, you will understand how to use pre-compiled models and how to prepare yours. This blog can also be considered as another tutorial for custom inference handlers.Deploying a pre-compiled modelLet's start with deploying an FHE-friendly model (prepared by Zama or third parties - see Preparing your pre-compiled model section below for learning how to prepare yours).First, look for the model you want to deploy: We have pre-compiled a bunch of models on Zama's HF page (or you can find them with tags). Let's suppose you have chosen concrete-ml-encrypted-decisiontree: As explained in the description, this pre-compiled model allows you to detect spam without looking at the message content in the clear.Like with any other model available on the Hugging Face platform, select Deploy and then Inference Endpoint (dedicated):Inference Endpoint (dedicated)Next, choose the Endpoint name or the region, and most importantly, the CPU (Concrete ML models do not use GPUs for now; we are working on it) as well as the best machine available - in the example below we chose eight vCPU. Now click on Create Endpoint and wait for the initialization to finish.Create EndpointAfter a few seconds, the Endpoint is deployed, and your privacy-preserving model is ready to operate.Endpoint is created: Don’t forget to delete the Endpoint (or at least pause it) when you are no longer using it, or else it will cost more than anticipated.Using the EndpointInstalling the client sideThe goal is not only to deploy your Endpoint but also to let your users play with it. For that, they need to clone the repository on their computer. This is done by selecting Clone Repository, in the dropdown menu:Clone RepositoryThey will be given a small command line that they can run in their terminal:git clone https://huggingface.co/zama-fhe/concrete-ml-encrypted-decisiontreeOnce the command is done, they go to the concrete-ml-encrypted-decisiontree directory and open play_with_endpoint.py with their editor. Here, they will find the line with API_URL = … and should replace it with the new URL of the Endpoint created in the previous section.API_URL = \"https://vtx9w974oxrq54ff.us-east-1.aws.endpoints.huggingface.cloud\"Of course, fill it in with with your Entrypoint’s URL. Also, define an access token and store it in an environment variable:export HF_TOKEN=[your token hf_XX..XX]Lastly, your user machines need to have Concrete ML installed locally: Make a virtual environment, source it, and install the necessary dependencies:python3.10 -m venv .venvsource .venv/bin/activatepip install -U setuptools pip wheelpip install -r requirements.txtRemark that we currently force the use of Python 3.10 (which is also the default python version used in Hugging Face Endpoints). This is because our development files currently depend on the Python version. We are working on making them independent. This should be available in a further version.Running inferencesNow, your users can run inference on the Endpoint launching the script:python play_with_endpoint.pyIt should generate some logs similar to the following:Sending 0-th piece of the key (remaining size is 71984.14 kbytes)Storing the key in the database under uid=3307376977Sending 1-th piece of the key (remaining size is 0.02 kbytes)Size of the payload: 0.23 kilobytesfor 0-th input, prediction=0 with expected 0 in 3.242 secondsfor 1-th input, prediction=0 with expected 0 in 3.612 secondsfor 2-th input, prediction=0 with expected 0 in 4.765 seconds(...)for 688-th input, prediction=0 with expected 1 in 3.176 secondsfor 689-th input, prediction=1 with expected 1 in 4.027 secondsfor 690-th input, prediction=0 with expected 0 in 4.329 secondsAccuracy on 691 samples is 0.8958031837916064Total time: 2873.860 secondsDuration per inference: 4.123 secondsAdapting to your application or needsIf you edit play_with_endpoint.py, you'll see that we iterate over different samples of the test dataset and run encrypted inferences directly on the Endpoint.for i in range(nb_samples):# Quantize the input and encrypt itencrypted_inputs = fhemodel_client.quantize_encrypt_serialize(X_test[i].reshape(1, -1))# Prepare the payloadpayload = {\"inputs\": \"fake\",\"encrypted_inputs\": to_json(encrypted_inputs),\"method\": \"inference\",\"uid\": uid,}if is_first:print(f\"Size of the payload: {sys.getsizeof(payload) / 1024:.2f} kilobytes\")is_first = False# Run the inference on HF serversduration -= time.time()duration_inference = -time.time()encrypted_prediction = query(payload)duration += time.time()duration_inference += time.time()encrypted_prediction = from_json(encrypted_prediction)# Decrypt the result and dequantizeprediction_proba = fhemodel_client.deserialize_decrypt_dequantize(encrypted_prediction)[0]prediction = np.argmax(prediction_proba)if verbose:print(f\"for {i}-th input, {prediction=} with expected {Y_test[i]} in {duration_inference:.3f} seconds\")# Measure accuracynb_good += Y_test[i] == predictionOf course, this is just an example of the Entrypoint's usage. Developers are encouraged to adapt this example to their own use-case or application.Under the hoodPlease note that all of this is done thanks to the flexibility of custom handlers, and we express our gratitude to the Hugging Face developers for offering such flexibility. The mechanism is defined in handler.py. As explained in the Hugging Face documentation, you can define the __call__ method of EndpointHandler pretty much as you want: In our case, we have defined a method parameter, which can be save_key (to save FHE evaluation keys), append_key (to save FHE evaluation keys piece by piece if the key is too large to be sent in one single call) and finally inference (to run FHE inferences). These methods are used to set the evaluation key once and then run all the inferences, one by one, as seen in play_with_endpoint.py.LimitsOne can remark, however, that keys are stored in the RAM of the Endpoint, which is not convenient for a production environment: At each restart, the keys are lost and need to be re-sent. Plus, when you have several machines to handle massive traffic, this RAM is not shared between the machines. Finally, the available CPU machines only provide eight vCPUs at most for Endpoints, which could be a limit for high-load applications.Preparing your pre-compiled modelNow that you know how easy it is to deploy a pre-compiled model, you may want to prepare yours. For this, you can fork one of the repositories we have prepared. All the model categories supported by Concrete ML (linear models, tree-based models, built-in MLP, PyTorch models) have at least one example, that can be used as a template for new pre-compiled models.Then, edit creating_models.py, and change the ML task to be the one you want to tackle in your pre-compiled model: For example, if you started with concrete-ml-encrypted-decisiontree, change the dataset and the model kind.As explained earlier, you must have installed Concrete ML to prepare your pre-compiled model. Remark that you may have to use the same python version than Hugging Face use by default (3.10 when this blog is written), or your models may need people to use a container with your python during the deployment.Now you can launch python creating_models.py. This will train the model and create the necessary development files (client.zip, server.zip, and versions.json) in the compiled_model directory. As explained in the documentation, these files contain your pre-compiled model. If you have any issues, you can get support on the fhe.org discord.The last step is to modify play_with_endpoint.py to also deal with the same ML task as in creating_models.py: Set the dataset accordingly.Now, you can save this directory with the compiled_model directory and files, as well as your modifications in creating_models.py and play_with_endpoint.py on Hugging Face models. Certainly, you will need to run some tests and make slight adjustments for it to work. Do not forget to add a concrete-ml and FHE tag, such that your pre-compiled model appears easily in searches.Pre-compiled models available todayFor now, we have prepared a few pre-compiled models as examples, hoping the community will extend this soon. Pre-compiled models can be found by searching for the concrete-ml or FHE tags.Model kindDatasetExecution time on HF EndpointLogistic RegressionSynthetic0.4 secDecisionTreeSpam2.0 secQNNIris3.7 secCNNMNIST24 secKeep in mind that there's a limited set of configuration options in Hugging Face for CPU-backed Endpoints (up to 8 vCPU with 16 GB of RAM today). Depending on your production requirements and model characteristics, execution times could be faster on more powerful cloud instances. Hopefully, more powerful machines will soon be available on Hugging Face Endpoints to improve these timings.Additional resourcesCheck out Zama libraries Concrete and Concrete-ML and start using FHE in your own applications.Check out Zama's Hugging Face profile to read more blog posts and try practical FHE demos.Check out @zama_fhe on twitter to get our latest updates.Conclusion and next stepsIn this blog post, we have shown that custom Endpoints are pretty easy yet powerful to use. What we do in Concrete ML is pretty different from the regular workflow of ML practitioners, but we are still able to accommodate the custom Endpoints to deal with most of our needs. Kudos to Hugging Face engineers for developing such a generic solution.We explained how:Developers can create their own pre-compiled models and make them available on Hugging Face models.Companies can deploy developers' pre-compiled models and make them available to their users via HF Endpoints.Final users can use these Endpoints to run their ML tasks over encrypted data.To go further, it would be useful to have more powerful machines available on Hugging Face Endpoints to make inferences faster. Also, we could imagine that Concrete ML becomes more integrated into Hugging Face's interface and has a Private-Preserving Inference Endpoint button, simplifying developers' lives even more. Finally, for integration in several server machines, it could be helpful to have a way to share a state between machines and keep this state non-volatile (FHE inference keys would be stored there)."}}},{"rowIdx":71,"cells":{"url":{"kind":"string","value":"https://huggingface.co/blog/rwkv"},"targets":{"kind":"string","value":"Introducing RWKV - An RNN with the advantages of a transformer"},"authors":{"kind":"string","value":"BlinkDL, Harrison Vanderbyl, Sylvain Gugger, Younes Belkada"},"date":{"kind":"string","value":"May 15, 2023"},"inputs":{"kind":"string","value":"ChatGPT and chatbot-powered applications have captured significant attention in the Natural Language Processing (NLP) domain. The community is constantly seeking strong, reliable and open-source models for their applications and use cases. The rise of these powerful models stems from the democratization and widespread adoption of transformer-based models, first introduced by Vaswani et al. in 2017. These models significantly outperformed previous SoTA NLP models based on Recurrent Neural Networks (RNNs), which were considered dead after that paper.Through this blogpost, we will introduce the integration of a new architecture, RWKV, that combines the advantages of both RNNs and transformers, and that has been recently integrated into the Hugging Face transformers library.Overview of the RWKV projectThe RWKV project was kicked off and is being led by Bo Peng, who is actively contributing and maintaining the project. The community, organized in the official discord channel, is constantly enhancing the project’s artifacts on various topics such as performance (RWKV.cpp, quantization, etc.), scalability (dataset processing & scrapping) and research (chat-fine tuning, multi-modal finetuning, etc.). The GPUs for training RWKV models are donated by Stability AI.You can get involved by joining the official discord channel and learn more about the general ideas behind RWKV in these two blogposts: https://johanwind.github.io/2023/03/23/rwkv_overview.html / https://johanwind.github.io/2023/03/23/rwkv_details.html Transformer Architecture vs RNNsThe RNN architecture is one of the first widely used Neural Network architectures for processing a sequence of data, contrary to classic architectures that take a fixed size input. It takes as input the current “token” (i.e. current data point of the datastream), the previous “state”, and computes the predicted next token, and the predicted next state. The new state is then used to compute the prediction of the next token, and so on.A RNN can be also used in different “modes”, therefore enabling the possibility of applying RNNs on different scenarios, as denoted by Andrej Karpathy’s blogpost, such as one-to-one (image-classification), one-to-many (image captioning), many-to-one (sequence classification), many-to-many (sequence generation), etc.Overview of possible configurations of using RNNs. Source: Andrej Karpathy's blogpost Because RNNs use the same weights to compute predictions at every step, they struggle to memorize information for long-range sequences due to the vanishing gradient issue. Efforts have been made to address this limitation by introducing new architectures such as LSTMs or GRUs. However, the transformer architecture proved to be the most effective thus far in resolving this issue.In the transformer architecture, the input tokens are processed simultaneously in the self-attention module. The tokens are first linearly projected into different spaces using the query, key and value weights. The resulting matrices are directly used to compute the attention scores (through softmax, as shown below), then multiplied by the value hidden states to obtain the final hidden states. This design enables the architecture to effectively mitigate the long-range sequence issue, and also perform faster inference and training compared to RNN models. Formulation of attention scores in transformer models. Source: Jay Alammar's blogpost Formulation of attention scores in RWKV models. Source: RWKV blogpost During training, Transformer architecture has several advantages over traditional RNNs and CNNs. One of the most significant advantages is its ability to learn contextual representations. Unlike the RNNs and CNNs, which process input sequences one word at a time, Transformer architecture processes input sequences as a whole. This allows it to capture long-range dependencies between words in the sequence, which is particularly useful for tasks such as language translation and question answering.During inference, RNNs have some advantages in speed and memory efficiency. These advantages include simplicity, due to needing only matrix-vector operations, and memory efficiency, as the memory requirements do not grow during inference. Furthermore, the computation speed remains the same with context window length due to how computations only act on the current token and the state.The RWKV architectureRWKV is inspired by Apple’s Attention Free Transformer. The architecture has been carefully simplified and optimized such that it can be transformed into an RNN. In addition, a number of tricks has been added such as TokenShift & SmallInitEmb (the list of tricks is listed in the README of the official GitHub repository) to boost its performance to match GPT. Without these, the model wouldn't be as performant.For training, there is an infrastructure to scale the training up to 14B parameters as of now, and some issues have been iteratively fixed in RWKV-4 (latest version as of today), such as numerical instability.RWKV as a combination of RNNs and transformersHow to combine the best of transformers and RNNs? The main drawback of transformer-based models is that it can become challenging to run a model with a context window that is larger than a certain value, as the attention scores are computed simultaneously for the entire sequence. RNNs natively support very long context lengths - only limited by the context length seen in training, but this can be extended to millions of tokens with careful coding. Currently, there are RWKV models trained on a context length of 8192 (ctx8192) and they are as fast as ctx1024 models and require the same amount of RAM.The major drawbacks of traditional RNN models and how RWKV is different:Traditional RNN models are unable to utilize very long contexts (LSTM can only manage ~100 tokens when used as a LM). However, RWKV can utilize thousands of tokens and beyond, as shown below:LM loss with respect to different context lengths and model sizes. Source: RWKV original repository Traditional RNN models cannot be parallelized when training. RWKV is similar to a “linearized GPT” and it trains faster than GPT.By combining both advantages into a single architecture, the hope is that RWKV can grow to become more than the sum of its parts.RWKV attention formulationThe model architecture is very similar to classic transformer-based models (i.e. an embedding layer, multiple identical layers, layer normalization, and a Causal Language Modeling head to predict the next token). The only difference is on the attention layer, which is completely different from the traditional transformer-based models.To gain a more comprehensive understanding of the attention layer, we recommend to delve into the detailed explanation provided in a blog post by Johan Sokrates Wind.Existing checkpointsPure language models: RWKV-4 modelsMost adopted RWKV models range from ~170M parameters to 14B parameters. According to the RWKV overview blog post, these models have been trained on the Pile dataset and evaluated against other SoTA models on different benchmarks, and they seem to perform quite well, with very comparable results against them.RWKV-4 compared to other common architectures. Source: Johan Wind's blogpost Instruction Fine-tuned/Chat Version: RWKV-4 RavenBo has also trained a “chat” version of the RWKV architecture, the RWKV-4 Raven model. It is a RWKV-4 pile (RWKV model pretrained on The Pile dataset) model fine-tuned on ALPACA, CodeAlpaca, Guanaco, GPT4All, ShareGPT and more. The model is available in multiple versions, with models trained on different languages (English only, English + Chinese + Japanese, English + Japanese, etc.) and different sizes (1.5B parameters, 7B parameters, 14B parameters). All the HF converted models are available on Hugging Face Hub, in the RWKV organization.🤗 Transformers integrationThe architecture has been added to the transformers library thanks to this Pull Request. As of the time of writing, you can use it by installing transformers from source, or by using the main branch of the library. The architecture is tightly integrated with the library, and you can use it as you would any other architecture.Let us walk through some examples below.Text Generation ExampleTo generate text given an input prompt you can use pipeline to generate text:from transformers import pipelinemodel_id = \"RWKV/rwkv-4-169m-pile\"prompt = \"In a shocking finding, scientist discovered a herd of dragons living in a remote, previously unexplored valley, in Tibet. Even more surprising to the researchers was the fact that the dragons spoke perfect Chinese.\"pipe = pipeline(\"text-generation\", model=model_id)print(pipe(prompt, max_new_tokens=20))>>> [{'generated_text': 'In a shocking finding, scientist discovered a herd of dragons living in a remote, previously unexplored valley, in Tibet. Even more surprising to the researchers was the fact that the dragons spoke perfect Chinese.The researchers found that the dragons were able to communicate with each other, and that they were'}]Or you can run and start from the snippet below:import torchfrom transformers import AutoModelForCausalLM, AutoTokenizermodel = AutoModelForCausalLM.from_pretrained(\"RWKV/rwkv-4-169m-pile\")tokenizer = AutoTokenizer.from_pretrained(\"RWKV/rwkv-4-169m-pile\")prompt = \"In a shocking finding, scientist discovered a herd of dragons living in a remote, previously unexplored valley, in Tibet. Even more surprising to the researchers was the fact that the dragons spoke perfect Chinese.\"inputs = tokenizer(prompt, return_tensors=\"pt\")output = model.generate(inputs[\"input_ids\"], max_new_tokens=20)print(tokenizer.decode(output[0].tolist()))>>> In a shocking finding, scientist discovered a herd of dragons living in a remote, previously unexplored valley, in Tibet. Even more surprising to the researchers was the fact that the dragons spoke perfect Chinese.The researchers found that the dragons were able to communicate with each other, and that they wereUse the raven models (chat models)You can prompt the chat model in the alpaca style, here is an example below:from transformers import AutoTokenizer, AutoModelForCausalLMmodel_id = \"RWKV/rwkv-raven-1b5\"model = AutoModelForCausalLM.from_pretrained(model_id).to(0)tokenizer = AutoTokenizer.from_pretrained(model_id)question = \"Tell me about ravens\"prompt = f\"### Instruction: {question}### Response:\"inputs = tokenizer(prompt, return_tensors=\"pt\").to(0)output = model.generate(inputs[\"input_ids\"], max_new_tokens=100)print(tokenizer.decode(output[0].tolist(), skip_special_tokens=True))>>> ### Instruction: Tell me about ravens### Response: RAVENS are a type of bird that is native to the Middle East and North Africa. They are known for their intelligence, adaptability, and their ability to live in a variety of environments. RAVENS are known for their intelligence, adaptability, and their ability to live in a variety of environments. They are known for their intelligence, adaptability, and their ability to live in a variety of environments.According to Bo, better instruction techniques are detailed in this discord message (make sure to join the channel before clicking)| |Weights conversionAny user could easily convert the original RWKV weights to the HF format by simply running the conversion script provided in the transformers library. First, push the \"raw\" weights to the Hugging Face Hub (let's denote that repo as RAW_HUB_REPO, and the raw file RAW_FILE), then run the conversion script:python convert_rwkv_checkpoint_to_hf.py --repo_id RAW_HUB_REPO --checkpoint_file RAW_FILE --output_dir OUTPUT_DIRIf you want to push the converted model on the Hub (let's say, under dummy_user/converted-rwkv), first forget to log in with huggingface-cli login before pushing the model, then run:python convert_rwkv_checkpoint_to_hf.py --repo_id RAW_HUB_REPO --checkpoint_file RAW_FILE --output_dir OUTPUT_DIR --push_to_hub --model_name dummy_user/converted-rwkvFuture workMulti-lingual RWKVBo is currently working on a multilingual corpus to train RWKV models. Recently a new multilingual tokenizer has been released.Community-oriented and research projectsThe RWKV community is very active and working on several follow up directions, a list of cool projects can be find in a dedicated channel on discord (make sure to join the channel before clicking the link). There is also a channel dedicated to research around this architecure, feel free to join and contribute!Model Compression and AccelerationDue to only needing matrix-vector operations, RWKV is an ideal candidate for non-standard and experimental computing hardware, such as photonic processors/accelerators.Therefore, the architecture can also naturally benefit from classic acceleration and compression techniques (such as ONNX, 4-bit/8-bit quantization, etc.), and we hope this will be democratized for developers and practitioners together with the transformers integration of the architecture.RWKV can also benefit from the acceleration techniques proposed by optimum library in the near future.Some of these techniques are highlighted in the rwkv.cpp repository or rwkv-cpp-cuda repository.AcknowledgementsThe Hugging Face team would like to thank Bo and RWKV community for their time and for answering our questions about the architecture. We would also like to thank them for their help and support and we look forward to see more adoption of RWKV models in the HF ecosystem.We also would like to acknowledge the work of Johan Wind for his blogpost on RWKV, which helped us a lot to understand the architecture and its potential.And finally, we would like to highlight anf acknowledge the work of ArEnSc for starting over the initial transformers PR.Also big kudos to Merve Noyan, Maria Khalusova and Pedro Cuenca for kindly reviewing this blogpost to make it much better!CitationIf you use RWKV for your work, please use the following cff citation."}}},{"rowIdx":72,"cells":{"url":{"kind":"string","value":"https://huggingface.co/blog/habana"},"targets":{"kind":"string","value":"Habana Labs and Hugging Face Partner to Accelerate Transformer Model Training"},"authors":{"kind":"string","value":"Susan Lansing"},"date":{"kind":"string","value":"April 12, 2022"},"inputs":{"kind":"string","value":"Habana Labs and Hugging Face Partner to Accelerate Transformer Model TrainingHugging FaceModelsDatasetsSpacesPostsDocsSolutionsPricingLog InSign UpBack to ArticlesHabana Labs and Hugging Face Partner to Accelerate Transformer Model Training"}}},{"rowIdx":73,"cells":{"url":{"kind":"string","value":"https://huggingface.co/blog/text-to-webapp"},"targets":{"kind":"string","value":"Making a web app generator with open ML models"},"authors":{"kind":"string","value":"Julian Bilcke"},"date":{"kind":"string","value":"July 3, 2023"},"inputs":{"kind":"string","value":"As more code generation models become publicly available, it is now possible to do text-to-web and even text-to-app in ways that we couldn't imagine before.This tutorial presents a direct approach to AI web content generation by streaming and rendering the content all in one go.Try the live demo here! → Webapp FactoryUsing LLM in Node appsWhile we usually think of Python for everything related to AI and ML, the web development community relies heavily on JavaScript and Node.Here are some ways you can use large language models on this platform.By running a model locallyVarious approaches exist to run LLMs in Javascript, from using ONNX to converting code to WASM and calling external processes written in other languages.Some of those techniques are now available as ready-to-use NPM libraries:Using AI/ML libraries such as transformers.js (which supports code generation)Using dedicated LLM libraries such as llama-node (or web-llm for the browser)Using Python libraries through a bridge such as PythoniaHowever, running large language models in such an environment can be pretty resource-intensive, especially if you are not able to use hardware acceleration.By using an APIToday, various cloud providers propose commercial APIs to use language models. Here is the current Hugging Face offering:The free Inference API to allow anyone to use small to medium-sized models from the community.The more advanced and production-ready Inference Endpoints API for those who require larger models or custom inference code.These two APIs can be used from Node using the Hugging Face Inference API library on NPM.💡 Top performing models generally require a lot of memory (32 Gb, 64 Gb or more) and hardware acceleration to get good latency (see the benchmarks). But we are also seeing a trend of models shrinking in size while keeping relatively good results on some tasks, with requirements as low as 16 Gb or even 8 Gb of memory.ArchitectureWe are going to use NodeJS to create our generative AI web server.The model will be WizardCoder-15B running on the Inference Endpoints API, but feel free to try with another model and stack.If you are interested in other solutions, here are some pointers to alternative implementations:Using the Inference API: code and spaceUsing a Python module from Node: code and spaceUsing llama-node (llama cpp): codeInitializing the projectFirst, we need to setup a new Node project (you can clone this template if you want to).git clone https://github.com/jbilcke-hf/template-node-express tutorialcd tutorialnvm usenpm installThen, we can install the Hugging Face Inference client:npm install @huggingface/inferenceAnd set it up in `src/index.mts``:import { HfInference } from '@huggingface/inference'// to keep your API token secure, in production you should use something like:// const hfi = new HfInference(process.env.HF_API_TOKEN)const hfi = new HfInference('** YOUR TOKEN **')Configuring the Inference Endpoint💡 Note: If you don't want to pay for an Endpoint instance to do this tutorial, you can skip this step and look at this free Inference API example instead. Please, note that this will only work with smaller models, which may not be as powerful.To deploy a new Endpoint you can go to the Endpoint creation page.You will have to select WizardCoder in the Model Repository dropdown and make sure that a GPU instance large enough is selected:Once your endpoint is created, you can copy the URL from this page:Configure the client to use it:const hf = hfi.endpoint('** URL TO YOUR ENDPOINT **')You can now tell the inference client to use our private endpoint and call our model:const { generated_text } = await hf.textGeneration({inputs: 'a simple \"hello world\" html page: '});Generating the HTML streamIt's now time to return some HTML to the web client when they visit a URL, say /app.We will create and endpoint with Express.js to stream the results from the Hugging Face Inference API.import express from 'express'import { HfInference } from '@huggingface/inference'const hfi = new HfInference('** YOUR TOKEN **')const hf = hfi.endpoint('** URL TO YOUR ENDPOINT **')const app = express()As we do not have any UI for the moment, the interface will be a simple URL parameter for the prompt:app.get('/', async (req, res) => {// send the beginning of the page to the browser (the rest will be generated by the AI)res.write('')const inputs = `# TaskGenerate ${req.query.prompt}# Out`for await (const output of hf.textGenerationStream({inputs,parameters: {max_new_tokens: 1000,return_full_text: false,}})) {// stream the result to the browserres.write(output.token.text)// also print to the console for debuggingprocess.stdout.write(output.token.text)}req.end()})app.listen(3000, () => { console.log('server started') })Start your web server:npm run startand open https://localhost:3000?prompt=some%20prompt. You should see some primitive HTML content after a few moments.Tuning the promptEach language model reacts differently to prompting. For WizardCoder, simple instructions often work best:const inputs = `# TaskGenerate ${req.query.prompt}# OrdersWrite application logic inside a JS tag.Use a central layout to wrap everything in a
# Out`Using TailwindTailwind is a popular CSS framework for styling content, and WizardCoder is good at it out of the box.This allows code generation to create styles on the go without having to generate a stylesheet at the beginning or the end of the page (which would make the page feel stuck).To improve results, we can also guide the model by showing the way ().const inputs = `# TaskGenerate ${req.query.prompt}# OrdersYou must use TailwindCSS utility classes (Tailwind is already injected in the page).Write application logic inside a JS tag.Use a central layout to wrap everything in a
# Out`Preventing hallucinationIt can be difficult to reliably prevent hallucinations and failures (such as parroting back the whole instructions, or writing “lorem ipsum” placeholder text) on light models dedicated to code generation, compared to larger general-purpose models, but we can try to mitigate it.You can try to use an imperative tone and repeat the instructions. An efficient way can also be to show the way by giving a part of the output in English:const inputs = `# TaskGenerate ${req.query.prompt}# OrdersNever repeat these instructions, instead write the final code!You must use TailwindCSS utility classes (Tailwind is already injected in the page)!Write application logic inside a JS tag!This is not a demo app, so you MUST use English, no Latin! Write in English! Use a central layout to wrap everything in a
# OutApp`Adding support for imagesWe now have a system that can generate HTML, CSS and JS code, but it is prone to hallucinating broken URLs when asked to produce images.Luckily, we have a lot of options to choose from when it comes to image generation models!→ The fastest way to get started is to call a Stable Diffusion model using our free Inference API with one of the public models available on the hub:app.get('/image', async (req, res) => {const blob = await hf.textToImage({inputs: `${req.query.caption}`,model: 'stabilityai/stable-diffusion-2-1'})const buffer = Buffer.from(await blob.arrayBuffer())res.setHeader('Content-Type', blob.type)res.setHeader('Content-Length', buffer.length)res.end(buffer)})Adding the following line to the prompt was enough to instruct WizardCoder to use our new /image endpoint! (you may have to tweak it for other models):To generate images from captions call the /image API: You can also try to be more specific, for example:Only generate a few images and use descriptive photo captions with at least 10 words!Adding some UIAlpine.js is a minimalist framework that allows us to create interactive UIs without any setup, build pipeline, JSX processing etc.Everything is done within the page, making it a great candidate to create the UI of a quick demo.Here is a static HTML page that you can put in /public/index.html:Tutorial
Generate
To make this work, you will have to make some changes:...// going to localhost:3000 will load the file from /public/index.htmlapp.use(express.static('public'))// we changed this from '/' to '/app'app.get('/app', async (req, res) => {...Optimizing the outputSo far we have been generating full sequences of Tailwind utility classes, which are great to give freedom of design to the language model.But this approach is also very verbose, consuming a large part of our token quota.To make the output more dense we can use Daisy UI, a Tailwind plugin which organizes Tailwind utility classes into a design system. The idea is to use shorthand class names for components and utility classes for the rest. Some language models may not have inner knowledge of Daisy UI as it is a niche library, in that case we can add an API documentation to the prompt:# DaisyUI docs## To create a nice layout, wrap each article in:
## Use appropriate CSS classes