<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by c-bata on Medium]]></title>
        <description><![CDATA[Stories by c-bata on Medium]]></description>
        <link>https://medium.com/@c-bata?source=rss-a9250c4c9905------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*0QIacUQ85_MduCEiY42XnQ.jpeg</url>
            <title>Stories by c-bata on Medium</title>
            <link>https://medium.com/@c-bata?source=rss-a9250c4c9905------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:59:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@c-bata/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Rustuna: A Faster Optuna Implementation in Rust]]></title>
            <link>https://medium.com/optuna/announcing-rustuna-cc82a6815bf7?source=rss-a9250c4c9905------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc82a6815bf7</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[optuna]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[c-bata]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 05:56:00 GMT</pubDate>
            <atom:updated>2026-09-07T07:23:30.848Z</atom:updated>
            <content:encoded><![CDATA[<p>Since Optuna was launched in 2018, it has expanded far beyond hyperparameter optimization for machine learning, growing into a versatile tool used across diverse domains. However, as adoption has scaled into increasingly complex fields, new challenges have emerged, most notably regarding execution speed and memory consumption during large-scale optimizations.</p><p>Inspired by the success of tools like <a href="https://github.com/astral-sh/ruff">Ruff</a>, <a href="https://github.com/pola-rs/polars">Polars</a>, and <a href="https://github.com/pydantic/pydantic">Pydantic V2</a>, which achieved dramatic performance improvements by leveraging Rust, we have developed and released Rustuna, a faster Optuna implementation built with Rust. In this post, we introduce Rustuna’s key features, how to use it, and our vision for its future.</p><ul><li>GitHub: <a href="https://github.com/optuna/rustuna/">https://github.com/optuna/rustuna/</a></li><li>Documentation: <a href="https://rustuna.readthedocs.io/">https://rustuna.readthedocs.io/</a></li></ul><p>Alongside Rustuna, we are also excited to announce Optuna 5.0, the fifth major release of Optuna. For full details on the new features and improvements, check out the <a href="https://medium.com/optuna/releasing-optuna-v5-0-an-open-source-black-box-optimization-library-9bff8b4587ba">Optuna 5.0 Release Blog</a>.</p><h3>Getting Started with Rustuna</h3><p>Rustuna provides high compatibility with Optuna. If you are already familiar with Optuna APIs, there is no need to learn a new API, so you can transition smoothly. Here is how to get started:</p><pre>$ pip install rustuna</pre><pre>import rustuna<br><br># 1. Define an objective function which returns a value you want to minimize.<br>def objective(trial: rustuna.Trial) -&gt; float:<br>    # 2. Define the search space via Suggest APIs.<br>    x = trial.suggest_float(&quot;x&quot;, -10, 10)<br>    y = trial.suggest_float(&quot;y&quot;, -10, 10)<br>    return (x - 2) ** 2 + (y + 5) ** 2<br><br># 3. Create a study which manages each experiment.<br>study = rustuna.create_study()<br><br># 4. Evaluate your objective function.<br>study.optimize(objective, n_trials=100)<br><br># 5. Print the best evaluation parameters.<br>print(study.best_trial)</pre><p>While Rustuna is not yet as feature-rich as Optuna, it already includes the core functionality most users need. Furthermore, except for a few specific features, Rustuna does not require Python dependencies. This minimal footprint helps mitigate risks associated with the recent surge in supply chain attacks. Even if execution speed or memory usage has never been a bottleneck for you, we encourage you to give it a try.</p><p>If you need features that Rustuna does not support, you can still leverage Optuna’s functionality. While certain use cases may not fully benefit from Rustuna’s speed advantages, this allows you to seamlessly use Optuna features, such as <a href="https://optuna.readthedocs.io/en/stable/reference/visualization/index.html">its visualization modules</a>, after executing an optimization. For details, please refer to the <a href="https://rustuna.readthedocs.io/en/latest/tutorial/getting-started/">official Rustuna documentation</a>.</p><h3>How Rustuna Got So Fast</h3><p>Rustuna was built with a strong focus on its execution speed. Figure 1 compares the execution speeds of the sampling algorithms provided by Rustuna and Optuna (measured on a MacBook with M4 Pro).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDFzofuA8SGkDw_Jt8Gu4Q.png" /><figcaption>Figure 1. Comparison of Sampler Execution Speed Between Optuna and Rustuna.</figcaption></figure><p>TPE and MOTPE (Multi-Objective TPE) are the default optimization algorithms used in Optuna. With TPE, the computation time required to sample parameters increases proportionally with the number of trials. While Optuna recommended using <a href="http://optuna.readthedocs.io/en/stable/reference/samplers/index.html">TPE primarily for runs under 1,000 trials</a>, Rustuna’s high-speed TPE implementation can complete 10,000 trials, ten times as many, in under a minute. This performance gap becomes even more pronounced when leveraging multi-threading (Table 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WlwUPjuMANU89MU8tHhyfw.png" /><figcaption>Table 1. Computation Time Scaling by Thread Count for Single-Objective TPE (Optuna vs. Rustuna). Evaluated at 1,000 trials across a 40-dimensional search space.</figcaption></figure><p>Algorithms like CMA-ES and NSGA-II also achieve massive speedups, but not simply because they were rewritten in Rust. Algorithmic theory dictates that sampling time for these methods should remain constant relative to trial count; however, due to architectural trade-offs, Optuna’s execution speed degrades as trial counts increase. Rustuna achieves its speed gains by combining two approaches: an optimized Rust implementation and a refined algorithmic architecture.</p><h3>Memory-efficient Storage Implementation</h3><p>Rustuna is also focused on optimizing memory consumption. In addition to performance gains achieved through lower-level architectural and implementation tuning, Rustuna differs significantly from Optuna by providing a feature to discard optimization histories that are no longer needed during optimization.</p><p>Unlike TPE or Gaussian Process-based Bayesian optimization algorithms, methods such as CMA-ES and NSGA-II only reference a subset of evaluation histories while running. However, Optuna retains all evaluation histories in memory indefinitely, causing both memory usage and execution time to degrade as the optimization progresses. By using the <em>apply_discard</em> option provided across Rustuna’s storage classes, unnecessary trial history is automatically purged from memory during the run.</p><pre>import rustuna<br><br>def objective(trial: rustuna.Trial) -&gt; float:<br>    x = trial.suggest_float(&quot;x&quot;, -10, 10)<br>    trial.set_user_attr(&quot;large_text&quot;, &quot;a&quot; * 10000)<br>    return (x - 2) ** 2<br><br># Set apply_discard=True to enable feature to discard trials.<br>storage = rustuna.storages.JournalFileStorage(&quot;./rustuna-journal.db&quot;, apply_discard=True)<br><br>sampler = rustuna.samplers.CmaEsSampler()<br>study = rustuna.create_study(sampler=sampler, storage=storage, study_name=&quot;example&quot;)<br>study.optimize(objective, n_trials=100000)</pre><p>While discarded during optimization, there are cases where you still want to analyze the complete evaluation history afterward. By loading the storage file without specifying the <em>apply_discard</em> option, the full history, including all previously discarded trials, can be loaded:</p><pre>storage = rustuna.storages.JournalFileStorage(&quot;./rustuna-journal.db&quot;)<br>study = rustuna.load_study(storage=storage, study_name=&quot;example&quot;)<br>print(study.best_trial)</pre><p>We also validated the impact of this feature in a real-world production service. Matlantis Corporation utilizes a custom NSGA-II-based method built on Optuna for their crystal structure prediction platform, Matlantis CSP (see: <a href="https://tech.preferred.jp/en/blog/matlantis-csp-and-optuna/">Crystal Structure Prediction Using Optuna in Matlantis CSP</a>). Figure 2 shows the impact on memory usage and execution speed after migrating to Rustuna.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7u5ywGoj5B1txyuuObdlyw.png" /><figcaption>Figure 2. Memory consumption (left) and average processing time per trial (right) in Matlantis CSP. With Optuna, both memory usage and execution time degrade significantly as the trial count increases.</figcaption></figure><p>With the Optuna implementation, memory consumption increases as evaluation histories accumulate over time. Furthermore, because their custom NSGA-II algorithm sequentially scans the complete evaluation history to extract necessary values, processing times degrade as the list grows.</p><p>In contrast, Rustuna’s <em>apply_discard</em> option discards unneeded trials, keeping memory growth minimal and preventing execution slowdowns even over long runs. This enables larger trial counts and greater parallelism. Based on these validation results, active development is now underway to fully integrate Rustuna into production.</p><h3>What’s Ahead</h3><p>Below is a look at our upcoming development roadmap for Rustuna. While Rustuna does not yet offer every capability available in Optuna, it already supports a wide range of essential features, including key optimization algorithms, storage backends, and hyperparameter importance calculations, making it fully capable of handling the vast majority of use cases.</p><p>To further improve usability and expand possibilities, we plan to focus on the following enhancements:</p><ol><li><strong>Improving Stability:</strong> Rustuna is still an emerging project, and new bugs are expected following this initial release. We plan to continuously refine and improve stability based on community feedback.</li><li><strong>Seamless Optuna Integration: </strong>Rustuna is not intended as a complete replacement for Optuna, nor is its goal to match Optuna’s vast feature set. Instead, it is designed to work in tandem with Optuna. We will continue strengthening integration so users can invoke Optuna features even more effortlessly.</li><li><strong>Multi-Language Support:</strong> Because Rustuna is implemented in Rust, it can easily target other languages via C APIs or WebAssembly. While development has focused primarily on Python bindings so far, we plan to explore support for Node.js and other ecosystems.</li></ol><p>Additionally, we plan to bring the architectural insights gained from Rustuna back into Optuna itself. Because Optuna supports a large ecosystem, maintaining backward compatibility is critical, requiring a careful, step-by-step approach to structural updates. However, several design changes introduced in Rustuna, such as bulk-insert storage APIs, <a href="https://rustuna.readthedocs.io/en/latest/migration/#studyenqueue_trial-and-the-trialqueue">trial queues</a>, and the <em>apply_discard</em> option, offer clear benefits for Optuna’s performance. We look forward to gradually porting these improvements back to Optuna while ensuring seamless compatibility.</p><h3>Conclusion</h3><p>In this post, we covered the background behind Rustuna’s development, how to get started, and its key advantages over Optuna.</p><p>For Rustuna to evolve into a mature and reliable software project, real-world usage and community feedback are vital. We invite you to give Rustuna a try, and if you encounter any issues or have suggestions, please feel free to open an issue on GitHub!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc82a6815bf7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/optuna/announcing-rustuna-cc82a6815bf7">Rustuna: A Faster Optuna Implementation in Rust</a> was originally published in <a href="https://medium.com/optuna">Optuna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optuna Dashboard Integrates with LLM: Enabling Data Filtering and Graph Generation using Natural…]]></title>
            <link>https://medium.com/optuna/optuna-dashboard-integrates-with-llm-enabling-data-filtering-and-graph-generation-using-natural-7d30669b2727?source=rss-a9250c4c9905------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d30669b2727</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[automl]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[optuna]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <dc:creator><![CDATA[c-bata]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 02:43:15 GMT</pubDate>
            <atom:updated>2025-11-17T02:43:15.509Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Optuna Dashboard Integrates with LLM: Enabling Data Filtering and Graph Generation using Natural Language</strong></h3><h3>Introduction</h3><p>Optuna Dashboard (GitHub: <a href="https://github.com/optuna/optuna-dashboard">https://github.com/optuna/optuna-dashboard</a>) is a web-based dashboard that makes it easy to review Optuna’s optimization history. As introduced in the <a href="https://medium.com/optuna/optuna-v5-roadmap-ac7d6935a878">Optuna v5 roadmap</a>, Optuna is currently enhancing its integration with large language models (LLMs) for its next major release. Introducing the LLM integration in Optuna Dashboard is one of its key milestones.</p><p>Optuna Dashboard v0.20.0 is the first version to support LLM integration. This article provides an overview of the newly introduced LLM integration features, along with details about the design and implementation considerations behind them.</p><h3>Overview of LLM Integration</h3><p>Enabling the LLM integration features currently makes the following two functionalities available:</p><ol><li>Natural language-based Trial filtering</li><li>Automatic chart generation</li></ol><p>The natural language-based Trial filtering function, illustrated in Figure 1, allows users to refine which Trials appear in graphs and tables using natural language. The traditional Optuna Dashboard only supported limited filter conditions. This is because implementing comprehensive filter options would significantly complicate the UI, making it less user-friendly. This new feature enables flexible filtering through simple UI by having the filter functions generated by LLM based on user instructions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oWC-l0sHmVe-qQTXqAIENg.png" /><figcaption>Figure 1: Natural language-based Trial filtering (in this example, only Trials with 2 or more layers and using the Adam optimizer are visualized)</figcaption></figure><p>The next feature is the automatic chart generation feature. Optuna Dashboard has supported generic charts useful for various optimization tasks, including visualizations of evaluation metric trends, Pareto front solutions, and contour plots. However, supporting visualization features specific to certain optimization tasks — which might be needed only for particular use cases — had been challenging. With the automatic chart generation feature, as shown in Figure 2, users can request specific visualizations, and the LLM will generate visualization functions using <a href="http://plotly.js">Plotly.js</a>, thereby enabling visualizations that were previously unsupported for task-specific use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CwCF63kzwqjQN0FIEtiVqw.png" /><figcaption>Figure 2: Example of using the automatic chart generation feature. The LLM used here is OpenAI’s GPT-5 Mini. The input prompt was: “Plot the intermediate values of all Trials in a study.”</figcaption></figure><p>For detailed instructions on using the LLM integration feature, please refer to the official documentation tutorial: <a href="https://optuna-dashboard.readthedocs.io/en/latest/tutorials/llm-integration.html">Tutorial: LLM Integration — Optuna Dashboard Documentation</a>.</p><h3>The Internal Execution Flow</h3><p>The two features mentioned earlier are very similar in terms of design and implementation. Visualizing their internal execution flow in a sequence diagram yields Figure 3 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k8WGNZK4iP97fkJ3gjpFpQ.png" /><figcaption>Figure 3: Execution flow for LLM integration in Optuna Dashboard</figcaption></figure><p>The system operates as follows: When a user inputs and submits instructions, the API server receives these texts. The server then generates a prompt based on a predefined template and queries the LLM Provider (such as the OpenAI API). The LLM Provider returns a string containing a JavaScript function that can be executed via eval(). The JavaScript function string is then displayed to the user for confirmation. If no issues are found, eval() is called, and the evaluation results are sent to the parent page via postMessage() for display.</p><p>The prompt template varies depending on the functionality but generally consists of four core elements:</p><ol><li>Filtering function generation instructions (e.g., “Please create a filtering function for …”)</li><li>TypeScript type definitions (e.g., type Trial = {trial_id: number; … })</li><li>Few-shot examples (see the source code for details)</li><li>(Only during retries) The function definition from previous evaluation attempts along with its error message</li></ol><p>For clarity in Figure 3, we omitted the details of retrying failed evaluations. When an LLM-generated JavaScript function evaluation fails, the system embeds the attempted function and error message back into the prompt template for retry. Many successful evaluations occur through retries, making this a practical feature.</p><p>When examining the overall execution flow, there are no particularly specialized aspects from a design perspective. However, a naive implementation would involve executing functions generated by the LLM via eval(), which raises certain risks and concerns. To address this, Optuna Dashboard incorporates several safeguards. Below, we’ll discuss these implementation-specific design considerations.</p><h3>Confirmation Dialog</h3><p>By design, Optuna Dashboard is not intended for public sharing among unrestricted users. Instead, it is meant to be used locally on individual computers or within trusted internal networks among limited members. Even so, fully trusting code generated by LLMs remains challenging, as there remains a risk of unintended behavior occurring.</p><p>One common mitigation approach is confirmation dialogs, similar to those implemented by Claude Desktop and various coding agents. Optuna Dashboard incorporates a confirmation dialog as shown in Figure 4, allowing users to examine the contents of JavaScript functions before execution and choose whether to proceed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*AHOkBmMhK_XZ4Gaio6Fogw.png" /><figcaption>Figure 4: Confirmation Dialog for the LLM-generated JavaScript code</figcaption></figure><p>The execution confirmation dialog includes a convenient “Never Ask Again” button. Upon clicking this button, the information is stored in the browser’s sessionStorage, preventing the dialog from appearing again in subsequent sessions. Unlike localStorage, sessionStorage is tied to individual browser tabs — allowing permission in one tab does not carry over to others, and the data is cleared when the tab is closed (see: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API#concepts_and_usage">Web Storage API</a>).</p><h3>Evaluating LLM-generated code inside the iframe-sandboxed environment</h3><p>Not all Optuna Dashboard users will be proficient in JavaScript, and visual inspection alone has inherent limitations. To complement the confirmation dialog, we implemented eval() execution within a sandboxed environment using &lt;iframe sandbox=”allow-scripts”&gt;&lt;/iframe&gt; tags.</p><p>As noted in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_direct_eval!">MDN’s documentation</a>, eval() can execute arbitrary JavaScript code, making it potentially dangerous if malicious code is passed to it. If such code were executed, it could read application variables or directly modify the DOM. Using an iframe tag creates a separate execution context that is isolated from the parent page, preventing direct access to the parent page’s DOM or JavaScript variables. Furthermore, by restricting all attributes except “allow-scripts” in the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/iframe#sandbox">sandbox attribute</a>, we can prevent issues like popup displays, form submissions, and access to localStorage/sessionStorage.</p><p>To illustrate this implementation in detail, we present a simplified excerpt from Optuna Dashboard’s source code below (the full source code is available <a href="https://github.com/optuna/optuna-dashboard/blob/29db3f5/tslib/react/src/hooks/useEvalFunctionInSandbox.tsx">here</a>). We embed an iframe tag as an invisible element on the page, sending the JavaScript function (as a string) to be evaluated along with the required parameters via postMessage(), and then return only the result of the eval() execution back to the parent page via postMessage().</p><pre>const iframeSrcDoc = `<br>    &lt;script&gt;<br>      window.fetch = () =&gt; { throw new Error(&quot;Unexpected&quot;) }<br>      window.XMLHttpRequest = () =&gt; { throw new Error(&quot;Unexpected&quot;) }<br>      window.addEventListener(&#39;message&#39;, (event) =&gt; {<br>        const { data } = event;<br>        if (typeof data !== &#39;object&#39; || data.type !== &#39;filter&#39;) return;<br>        const { trials, filterFuncStr } = data;<br>        try {<br>          const filterFunc = eval(&#39;(&#39; + filterFuncStr + &#39;)&#39;);<br>          const result = trials.filter(filterFunc);<br>          parent.postMessage({ type: &#39;result&#39;, filteredTrials: result }, &#39;*&#39;);<br>        } catch (e) {<br>          parent.postMessage({ type: &#39;result&#39;, filteredTrials: [], error: String(e) }, &#39;*&#39;);<br>        }<br>      });<br>    &lt;/script&gt;<br>  `<br>return (<br>  &lt;iframe<br>    ref={iframeRef}<br>    sandbox=&quot;allow-scripts&quot;<br>    style={{ display: &quot;none&quot; }}<br>    srcDoc={iframeSrcDoc}<br>  /&gt;<br>)</pre><p>Important note: The sandboxed environment provided by iframe tags does not eliminate all security concerns. For example, iframe tags alone cannot restrict external network communications using the fetch API, requiring additional measures like Content Security Policy (CSP) to control network access.</p><h3>Conclusion</h3><p>This article introduced the overview and internal design/implementation details of our LLM integration feature. The LLM-based trial filtering enables flexible filtering through an extremely simple UI, while the automatic generation of Plotly charts based on user requests would have been nearly impossible to achieve without LLM integration. Our LLM integration features still have significant room for further development, and we plan to continue refining them in preparation for Optuna v5.</p><p>If you’ve found this article interesting and would like to try out the LLM integration functionality, please refer to <a href="https://optuna-dashboard.readthedocs.io/en/latest/tutorials/llm-integration.html">the tutorial</a> and we’d greatly appreciate your feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d30669b2727" width="1" height="1" alt=""><hr><p><a href="https://medium.com/optuna/optuna-dashboard-integrates-with-llm-enabling-data-filtering-and-graph-generation-using-natural-7d30669b2727">Optuna Dashboard Integrates with LLM: Enabling Data Filtering and Graph Generation using Natural…</a> was originally published in <a href="https://medium.com/optuna">Optuna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Announcing Optuna 4.2]]></title>
            <link>https://medium.com/optuna/announcing-optuna-4-2-98148689e626?source=rss-a9250c4c9905------2</link>
            <guid isPermaLink="false">https://medium.com/p/98148689e626</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[optuna]]></category>
            <dc:creator><![CDATA[c-bata]]></dc:creator>
            <pubDate>Mon, 20 Jan 2025 07:27:30 GMT</pubDate>
            <atom:updated>2025-01-20T07:27:30.981Z</atom:updated>
            <content:encoded><![CDATA[<p>We are pleased to announce the release of Optuna 4.2! Optuna 4.2 now supports several new optimization algorithms, a gRPC storage proxy for large-scale hyperparameter optimization, and benchmark functions. This blog will walk you through these updates and explain how to utilize the new features. Let’s take a closer look at these new and improved features.</p><p>Please try upgrading to the latest versions of Optuna and OptunaHub!</p><pre>$ pip install -U optuna optunahub</pre><h3>gRPC Storage Proxy for RDBStorage</h3><p>We’ve made performance improvements for large-scale distributed optimization. For example, our previous release, v4.1, delivered significant performance improvements, as shown in Table 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h4boYGex44rxJ8q_fbwOAg.png" /><figcaption>Table 1: Comparison of the RDBStorage’s speed benchmark between v4.0 and v4.1.</figcaption></figure><p>However, in cases where the RDB server becomes heavily loaded due to more large-scale distributed optimization that involves a large number of workers, overcoming this problem through query tuning or RDB server parameter tuning can be challenging. The gRPC storage proxy is a feature designed to support such large-scale distributed optimization. The conceptual diagram is shown in Figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jb1WIn3hBcKZV8uJkPEevA.png" /><figcaption>Figure 1: The Conceptual Diagram for Using the gRPC Storage Proxy</figcaption></figure><p>As shown in Figure 1, the gRPC storage proxy sits between the optimization workers and the database server, proxying the calls of Optuna’s storage APIs. In large-scale distributed optimization settings where hundreds to thousands of workers are operating, placing a gRPC storage proxy for every few tens can significantly reduce the load on the RDB server which would otherwise be a single point of failure. The gRPC storage proxy enables sharing the cache about Optuna studies and trials, which can further mitigate load.</p><p>We conducted performance comparisons with the following setup. We prepared a MySQL server, placed a proxy server every ten for 300 workers to relay the storage API calls, conducted a distributed optimization of 10,000 Trials using the RandomSampler. Table 2 shows the average time taken per worker. In this scenario, we were able to reduce the processing time by about 60%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n6wulzOuR-LDTXObjhwS5Q.png" /><figcaption>Table 2: Speed Comparison of the gRPC Proxy where 300 Workers Are Running</figcaption></figure><p>It’s important to note that the gRPC storage proxy could be slower in cases where the number of workers are not so huge as the load on MySQL is not too heavy. Indeed, we confirmed a slowdown of about 1.2–1.3 times with a single worker. Please be aware that the gRPC Storage Proxy is specifically designed to streamline large-scale distributed optimization.</p><p>By using the gRPC storage proxy, it is possible to reduce the load on the database server when conducting large-scale distributed optimization. Please refer to <a href="https://optuna.readthedocs.io/en/latest/reference/generated/optuna.storages.GrpcStorageProxy.html#optuna.storages.GrpcStorageProxy">the official documentation</a> for further details on how to utilize the gRPC storage proxy.</p><h3>SMAC3: Random Forest-Based Bayesian Optimization Developed by AutoML.org</h3><p>SMAC3 [1] is a hyperparameter optimization framework developed by <a href="http://automl.org">AutoML.org</a>, one of the most influential AutoML research groups. The Optuna-compatible SMAC3 sampler is now available thanks to the contribution to OptunaHub by Difan Deng (<a href="https://github.com/dengdifan">@dengdifan</a>), one of the core members of AutoML.org. We can now use the method widely used in AutoML research and real-world applications from Optuna, hopefully reducing the implementational effort even if it is a little. We show the basic usage of SMACSampler from Optuna below:</p><pre>$ pip install optunahub smac==2.2.0</pre><pre>import optuna<br>import optunahub<br>from optuna.distributions import FloatDistribution<br><br><br>def objective(trial: optuna.Trial) -&gt; float:<br>    x = trial.suggest_float(&quot;x&quot;, -10, 10)<br>    y = trial.suggest_float(&quot;y&quot;, -10, 10)<br>    return x**2 + y**2<br><br><br>smac_mod = optunahub.load_module(&quot;samplers/smac_sampler&quot;)<br>n_trials = 100<br>sampler = smac_mod.SMACSampler(<br>    {&quot;x&quot;: FloatDistribution(-10, 10), &quot;y&quot;: FloatDistribution(-10, 10)},<br>    n_trials=n_trials,<br>)<br>study = optuna.create_study(sampler=sampler)<br>study.optimize(objective, n_trials=n_trials)</pre><p>Please check <a href="https://hub.optuna.org/samplers/smac_sampler/">the OptunaHub SMAC3 page</a> and try it out!</p><p>[1] M. Lindauer, K. Eggensperger, M. Feurer, A. Biedenkapp, D. Deng, C. Benjamins, R. Sass, and F. Hutter. SMAC3: A Versatile Bayesian Optimization Package for Hyperparameter Optimization. Journal of Machine Learning Research, 23(54), 1–9.</p><h3>OptunaHub Now Supports Benchmark Functions</h3><p>Benchmarking the performance of optimization algorithms is an essential process indispensable to the research and development of algorithms. The newly added <a href="https://hub.optuna.org/?q=Benchmark">benchmark in OptunaHub v0.2.0</a>, released in conjunction with Optuna v4.2, is a new feature for users to conduct benchmarks conveniently.</p><p>In the following sample code, we compare and display the performance of the four kinds of samplers using a two-dimensional Sphere function, which is part of a group of benchmark functions widely used in the black-box optimization research community known as Blackbox Optimization Benchmarking (BBOB). The output image is shown in Figure 2.</p><pre>import optuna<br>import optunahub<br><br>bbob_mod = optunahub.load_module(&quot;benchmarks/bbob&quot;)<br>smac_mod = optunahub.load_module(&quot;samplers/smac_sampler&quot;)<br>sphere2d = bbob_mod.Problem(function_id=1, dimension=2)<br><br>n_trials = 100<br>studies = []<br>for study_name, sampler in [<br>    (&quot;random&quot;, optuna.samplers.RandomSampler(seed=1)),<br>    (&quot;tpe&quot;, optuna.samplers.TPESampler(seed=1)),<br>    (&quot;cmaes&quot;, optuna.samplers.CmaEsSampler(seed=1)),<br>    (&quot;smac&quot;, smac_mod.SMACSampler(sphere2d.search_space, n_trials, seed=1)),<br>]:<br>    study = optuna.create_study(directions=sphere2d.directions,<br>        sampler=sampler, study_name=study_name)<br>    study.optimize(sphere2d, n_trials=n_trials)<br>    studies.append(study)<br><br>optuna.visualization.plot_optimization_history(studies).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*htyTBUXqHrQdnSF7r1rAwg.png" /><figcaption>Figure 2: Result of benchmarking</figcaption></figure><p>By using OptunaHub Benchmarks, you can easily benchmark algorithms using various problems. Besides the purposes of research and development of algorithms, this feature can be used for preliminary experiments before tackling real-world problems and as toy problems during algorithm learning, among other use cases. We hope you will find it very useful!</p><h3>Gaussian Process-Based Bayesian Optimization with Inequality Constraints</h3><p>Optuna has supported Gaussian process-based Bayesian optimization sampler, i.e., GPSampler, since Optuna 3.6. Please check <a href="https://medium.com/optuna/introducing-optunas-native-gpsampler-0aa9aa3b4840">the past article</a> for more details. Since Gaussian process-based Bayesian optimization is a very popular method in various research fields such as aircraft engineering and materials science, we worked on its extension and adapted GPSampler to constrained optimization [1,2] in Optuna 4.2. We show the basic usage below:</p><pre>$ pip install optuna==4.2.0<br># GPSampler requires scipy and torch along with the Optuna dependencies.<br>$ pip install scipy<br>$ pip install torch - extra-index-url https://download.pytorch.org/whl/cpu</pre><pre>import numpy as np<br>import optuna<br><br><br>def objective(trial: optuna.Trial) -&gt; float:<br>    x = trial.suggest_float(&quot;x&quot;, 0.0, 2 * np.pi)<br>    y = trial.suggest_float(&quot;y&quot;, 0.0, 2 * np.pi)<br>    c = float(np.sin(x) * np.sin(y) + 0.95)<br>    trial.set_user_attr(&quot;c&quot;, c)<br>    return float(np.sin(x) + y)<br><br><br>def constraints(trial: optuna.trial.FrozenTrial) -&gt; tuple[float]:<br>    return (trial.user_attrs[&quot;c&quot;],)<br><br><br>sampler = optuna.samplers.GPSampler(constraints_func=constraints)<br>study = optuna.create_study(sampler=sampler)<br>study.optimize(objective, n_trials=50)</pre><p>We compared the optimization performance between the constrained GPSamplerand Optuna’s default sampler for constrained optimization (TPESampler). The comparison result is shown in Figure 3. Since this problem is with a low budget and a numerical search space, GPSampler outperforms TPESampler. Please try out GPSampler for constrained optimization especially when only a small number of trials are available!</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*P7ijCB83ETCHetk6" /><figcaption>Figure 3: Performance comparison between a constrained GPSampler and the Optuna default sampler for constrained optimization (TPESampler). We used Simulation 2 proposed by J. Gardner et al. [1] and ran the experiments over 10 random seeds. The horizontal axis represents the number of trials and the vertical axis represents the feasible objective value. Since this problem is with a low budget and a numerical search space, GPSampler outperforms TPESampler.</figcaption></figure><p>[1] J. Gardner, M. Kusner, ZE. Xu, K. Weinberger, and J. Cunningham. Bayesian optimization with inequality constraints. In International Conference on Machine Learning, 2014.<br>[2] M. Gelbart, J. Snoek, and R. Adams. Bayesian optimization with unknown constraints. arXiv:1403.5607, 2014.</p><h3>c-TPE: Support Constrained TPESampler</h3><p>Although Optuna has supported constrained optimization for TPESampler, which is the default Optuna sampler, since v3.0.0, its algorithm design and performance comparison have not been verified academically. OptunaHub now supports c-TPE [1], which is another constrained optimization method for TPESampler. Importantly, the algorithm design and its performance comparison are publicly reviewed to be accepted to IJCAI, a top-tier AI international conference. Here is the usage example of c-TPE.</p><pre>$ pip install optunahub</pre><pre>import numpy as np<br>import optuna<br>import optunahub<br><br><br>def objective(trial: optuna.Trial) -&gt; float:<br>    x = trial.suggest_float(&quot;x&quot;, 0.0, 2 * np.pi)<br>    y = trial.suggest_float(&quot;y&quot;, 0.0, 2 * np.pi)<br>    c = float(np.sin(x) * np.sin(y) + 0.95)<br>    trial.set_user_attr(&quot;c&quot;, c)<br>    return float(np.sin(x) + y)<br><br><br>def constraints(trial: optuna.trial.FrozenTrial) -&gt; tuple[float]:<br>    return (trial.user_attrs[&quot;c&quot;],)<br><br><br>sampler = optunahub.load_module(&quot;samplers/ctpe&quot;).cTPESampler(<br>    constraints_func=constraints<br>)<br>study = optuna.create_study(sampler=sampler)<br>study.optimize(objective, n_trials=50)</pre><p>As shown in Table 3, cTPESampleroutperforms TPESampler. One of the advantages of cTPESampler over, for example, GPSampler is a light-weight sampling, enabling more n_trials. If you need a performant, yet light-weight, sampler for constrained optimization, please use cTPESampler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1kX2CwOgkeqjShU5MrOKKg.png" /><figcaption>Table 3: The comparison between the default constrained TPESampler supported by Optuna and cTPESampler. Each sampler optimized 54 types of 5D constrained optimization problems available in bbob-constrained with the optimization budget of 100 Trials. Each row shows the number of problems where each sampler outperformed the other w.r.t. best_trial.value with the budget of N trials. Note that we compared the medians of best_trial.value over 10 different studies. For example, cTPESampler could outperform TPESampler for 46 problems with a budget of 100 Trials. Please notice that since TPESampler and cTPESampler tied for some problems, the summations of each row do not become 54.</figcaption></figure><p>[1] S. Watanabe and F. Hutter. c-TPE: Tree-Structured Parzen Estimator with Inequality Constraints for Expensive Hyperparameter Optimization. International Joint Conference on Artificial Intelligence (IJCAI), 2023.</p><h3>What’s Ahead</h3><p>With the release of Optuna 4.2, we’ve utilized OptunaHub, our feature-sharing platform, to introduce new state-of-the-art algorithms. In addition, we’ve introduced a new feature specifically for users who require large-scale distributed optimization, such as gRPC storage proxy.</p><p>As we consistently roll out new features and improvements, we are also starting preparations for our next major release, v5. Please note that v5.0 is still a while away (at least a year). At Optuna, we believe that feedback and feature requests from users are very important. If you have any requests or ideas for v5, we would be delighted to get your feedback on the GitHub Discussion linked below.</p><p><a href="https://github.com/optuna/optuna/discussions/5930">https://github.com/optuna/optuna/discussions/5930</a></p><h3>Contributors</h3><p>As with any other release, this one would not have been possible without the feedback, code, and comments from many contributors.</p><p>@HideakiImamura, @JLX0, @KannanShilen, @SimonPop, @boringbyte, @c-bata, @fusawa-yugo, @gen740, @himkt, @iamarunbrahma, @kAIto47802, @ktns, @mist714, @nabenabe0928, @not522, @nzw0301, @porink0424, @sawa3030, @sulan, @unKnownNG, @willdavidson05, @y0z</p><p>Thanks to those who have followed the projects from the very early days and those who have joined along the way.</p><h3>Next Step</h3><p>Check out the <a href="https://github.com/optuna/optuna/releases/tag/v4.2.0">release notes</a> for more information. To get the latest news from Optuna, follow us on <a href="https://x.com/OptunaAutoML">X.com</a>. For feedback, please file an issue or create a pull request on <a href="https://github.com/optuna/optuna">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98148689e626" width="1" height="1" alt=""><hr><p><a href="https://medium.com/optuna/announcing-optuna-4-2-98148689e626">Announcing Optuna 4.2</a> was originally published in <a href="https://medium.com/optuna">Optuna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prototyping a Faster Optuna Implementation in Rust]]></title>
            <link>https://medium.com/optuna/prototyping-a-faster-optuna-implementation-in-rust-e76efba3761b?source=rss-a9250c4c9905------2</link>
            <guid isPermaLink="false">https://medium.com/p/e76efba3761b</guid>
            <category><![CDATA[automl]]></category>
            <category><![CDATA[libraries]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[optuna]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[c-bata]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 05:44:00 GMT</pubDate>
            <atom:updated>2024-03-26T05:44:00.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9J0Fr7bR6c4jxZA5-LXDw.png" /></figure><h3>Introduction</h3><p>Optuna is implemented entirely in Python without relying on C extensions. It enjoys smooth installation across various execution environments — a critical attribute given its widespread usage. At the moment, we have no plans to depend on non-Python languages.</p><p>On the other hand, there have been several use cases where execution speed matters, or where we would like to integrate existing systems coded by another language. With the recent notable speed enhancements in Python toolchains, especially <a href="https://astral.sh/ruff">Ruff</a> which uses Rust, we have started closed-source prototyping of Optuna implementation in Rust. While we are not currently planning for a public release, this blog outlines the motivation behind this development and the potential benefits that a Rust-based Optuna implementation could provide.</p><h3>Motivation</h3><p>The Optuna implementation in Rust is primarily motivated by two factors.</p><p><strong>Making Optuna Faster</strong></p><p>Optuna primarily targets hyperparameter optimization in machine learning. In such scenarios, model training and evaluation are typically time-consuming processes, so Optuna’s execution time seldom becomes the bottleneck.</p><p>However, there are many possible applications of black-box optimization beyond the optimization of machine learning hyperparameters. For example, in the case presented below where Optuna is used in the field of material science to explore unknown crystal structures, the execution speed of Optuna becomes critical because many trials are required. The more iterations conducted, the higher the probability of finding unknown crystal structures.<br><a href="https://www.mrs.org/meetings-events/presentation/2023_mrs_fall_meeting/2023_mrs_fall_meeting-3957399">Efficient Crystal Structure Prediction using Universal Neural Network Potential and Genetic Algorithm</a></p><p><strong>Broadening Language Support</strong></p><p>The Rust-based implementation can be used not only from Rust and Python, but also provides JavaScript bindings and a C-API. In particular, we aim to utilize the JavaScript bindings in Optuna Dashboard.</p><p><a href="https://github.com/optuna/optuna-dashboard">Optuna Dashboard</a> is a web dashboard used to analyze Optuna trial results. We also recently started providing <a href="https://medium.com/optuna/the-internal-of-optunas-jupyter-lab-and-vs-code-extensions-5b29da7da7b6">extensions for Jupyter Lab and VS Code</a>.</p><p>While implementing these, we have re-implemented various logics in TypeScript, including the visualization module (optuna.visualization) and the JournalFileStorage loader implemented in Optuna. Some of these have speed issues, and it is expected that the Rust-based implementation can improve the user experience by providing fast JavaScript bindings. There are also development benefits, which we will detail later.</p><h3>Accelerating Optuna Using Rust-based Implementation</h3><p>In our prototype of the Rust-based Optuna implementation, we have re-implemented the core functionality of Optuna in Rust while also facilitating Python bindings using PyO3. This section elaborates on the implementation policy of the Rust-based Optuna implementation and its execution speed as of now.</p><p><strong>Compatibility and Speed Comparison with Optuna</strong></p><p>As Ruff provides high compatibility with existing toolchains, the Rust-based Optuna implementation also emphasizes compatibility with the Optuna API. Users don’t need to learn a new API, they can straightforwardly transition from existing projects and continue to reap the benefits of the ecosystem that Optuna has built. Since the Rust-based Optuna implementation provides essentially the same API as Optuna, the following code works as is, by just changing the import statement.</p><pre>import &lt;OPTUNA_RUST&gt; as optuna<br><br><br>def objective(trial:optuna.Trial) -&gt; float:<br>    x = trial.suggest_float(&#39;x&#39;, -10, 10)<br>    y = trial.suggest_float(&#39;y&#39;, -10, 10)<br>    value = (x - 2) ** 2 + (y + 5) ** 2<br>    return value<br><br><br>study = optuna.create_study()<br>study.optimize(objective, n_trials=1000)<br>print(study.best_trial)</pre><p>The current performance comparison for the above code, when varying the number of trials and parameters, is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1oDXeanl3udF661I45FSg.png" /><figcaption>TPESampler (multivariate=False)</figcaption></figure><p>Optuna uses TPESampler by default. As <a href="https://optuna.readthedocs.io/en/stable/reference/samplers/index.html">the comparison table</a> in the official documentation suggests a recommended budget of 100–1000 for the TPESampler, the TPE is not necessarily the suitable method when many trials can be evaluated from the perspectives of computational complexity and optimization performance. If we have an abundant computational budget, other methods are often recommended. For example, the comparison of execution times for the RandomSampler is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i7TcfbuNfYSa99ABh6bStA.png" /><figcaption>RandomSampler</figcaption></figure><p>One key observation from the above results is that when we increase the number of trials tenfold, the execution time of the Rust-based implementation only takes about ten times longer. In contrast, the execution time of Optuna increases by 50 to 100 times. This can be attributed to some of the convenient features provided by Optuna. At Optuna, we carefully balance convenience and speed reduction in our development, but it is also true that as a result of pursuing convenience for many users, we have caused such slow-down problems for some users.</p><p>The Rust-based implementation puts a high priority on speed. If there isn’t a significant speed improvement, the Rust-based implementation is not necessary. If we heavily focus on compatibility with the Optuna design and its functionalities, Rust-based implementation may not be able to achieve significant performance improvements. Hence, we are carefully considering the implementation of certain features, such as <a href="https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.Study.html#optuna.study.Study.enqueue_trial">enqueue_trial()</a>. This is one of the reasons why I mentioned that the Rust-based implementation provides “essentially” the same API.</p><p><strong>Integration of Optuna (Python) and Its Rust-Based Implementation</strong></p><p>The Rust-based implementation is not aimed to serve as a complete replacement for Optuna. Instead of re-engineering all of Optuna’s features in Rust, we aim to create a cooperative library where the strengths of each can be utilized and complement each other.</p><p>For instance, RDBStorage is an important feature in Optuna. It enables the persistence of trial results and distributed optimization. However, re-implementing this feature in Rust presents only a minimal advantage. The main bottleneck lies in I/O operations, which don’t typically benefit from re-implementation in terms of speed. Consequently, the Rust implementation of Optuna offers conversion utilities to avoid redeveloping such features.</p><pre>import &lt;OPTUNA_RUST&gt; as optuna<br>from &lt;OPTUNA_RUST&gt; import FromOptunaStorage<br>from optuna.storages import RDBStorage<br><br><br>def objective(trial: optuna.Trial) -&gt; float:<br>    ...<br><br><br>storage = FromOptunaStorage(RDBStorage(&quot;sqlite://db.sqlite3&quot;))<br>study = optuna.create_study(storage=storage, study_name=&quot;example&quot;)<br>study.optimize(objective, n_trials=10)</pre><p>In the example above, we are partly leveraging Optuna’s capabilities from the Rust-based implementation. The opposite is also possible. The following code illustrates partially utilizing the Rust-based implementation within Optuna.</p><pre>import optuna<br><br># from optuna.importance import FanovaImportanceEvaluator<br>from &lt;OPTUNA_RUST&gt;.optuna.importance import FanovaImportanceEvaluator<br><br><br>def objective(trial: optuna.Trial) -&gt; float:<br>    ...<br><br><br>study = optuna.create_study()<br>study.optimize(objective)<br><br>importance = optuna.importance.get_param_importances(<br>    study, evaluator=FanovaImportanceEvaluator()<br>)</pre><p>Though this approach has some limitations in terms of speed improvement compared to the previous one, it allows you to try the Rust-based implementation more easily without significantly rewriting existing code. If any problem arises or the performance advantages aren’t realized, it’s much easier to switch back.</p><h3>Handling Technical Challenges in Optuna Dashboard</h3><p>Lastly, I will introduce the vision for utilization in the Optuna Dashboard. The Optuna Dashboard is a web application for viewing Optuna trial results. The development of this web dashboard involves two major technical challenges: improving execution speed and streamlining the process of unit testing.</p><p><strong>Making Optuna Dashboard Faster</strong></p><p>The Optuna Dashboard consists of a Python API server and a Single Page Application (SPA). The main role of the API server is to just deliver Studies and Trials to the web frontend via a JSON API so that most of the important application logics are implemented in the single page application using TypeScript. This greatly contributes to the simplicity of the design of Optuna Dashboard and the improvement of user experience, and is also very useful for providing the <a href="https://medium.com/optuna/the-internal-of-optunas-jupyter-lab-and-vs-code-extensions-5b29da7da7b6">VS Code extension</a>.</p><p>However, unfortunately, the current Optuna Dashboard is quite slow and hard to use when dealing with tens of thousands of trials. There are several fundamental factors for this, but if the Rust-based implementation provides fast JavaScript bindings, Optuna Dashboard will become faster while maintaining the current simple design and improving the user experience.</p><p><strong>Writing Maintainable Unit Tests</strong></p><p>Most of the frontend logics of the Optuna Dashboard takes a list of Optuna Trials as arguments. Trials contain a lot of necessary information, such as params and distributions, which can make the setup code wordy and complicated when generating multiple trials. Introducing utilities for generating fixtures can be considered, but there are concerns that this itself can become bloated and create a debt of not knowing what is being tested.</p><p>By providing JavaScript bindings for the Rust-based implementation, we can easily generate Study or Trial information on the Node.js side for testing. There is no need to hardcode distributions or internal_params etc. to prepare Trials, making it strong against changes in internal structure and improving the maintainability of unit tests.</p><pre>import * as optuna from &#39;&lt;OPTUNA_RUST&gt;.js&#39;;<br><br><br>const study = optuna.create_study();<br>const objective = (trial) =&gt; {<br>    const x = trial.suggest_float(&quot;x&quot;, -10.0, 10.0);<br>    const y = trial.suggest_int(&quot;y&quot;, -10, 10);<br>    const z = trial.suggest_categorical(&quot;z&quot;, [&quot;foo&quot;, &quot;bar&quot;]);<br>    return value = (x - 5) ** 2 + (y + 2) ** 2<br>}<br><br>study.optimize(objective, 10)<br>console.log(study.best_trial())</pre><p>Until now, development in Optuna Dashboard has heavily depended on E2E testing, executing Optuna, saving trial results into SQLite3, launching the actual Python API server, and validating the display with pytest and Playwright. While E2E testing allows us to test Optuna Dashboard easily, this approach is not suitable to increase the test coverage. Providing the JavaScript bindings allows us to write maintainable unit tests, leading to improved test coverage.</p><h3>Conclusion</h3><p>In this article, I introduced the motivation and vision for the utilization of the newly initiated Rust-based Optuna implementation. As mentioned at the beginning, the Rust-based Optuna implementation is still in the prototype stage, and there are no specific plans for public release at this time. We plan to continue developing and verifying its usefulness within the committers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e76efba3761b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/optuna/prototyping-a-faster-optuna-implementation-in-rust-e76efba3761b">Prototyping a Faster Optuna Implementation in Rust</a> was originally published in <a href="https://medium.com/optuna">Optuna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Internal of Optuna’s Jupyter Lab and VS Code Extensions]]></title>
            <link>https://medium.com/optuna/the-internal-of-optunas-jupyter-lab-and-vs-code-extensions-5b29da7da7b6?source=rss-a9250c4c9905------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b29da7da7b6</guid>
            <category><![CDATA[optuna]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[vs-code-extensions]]></category>
            <category><![CDATA[jupyterlab]]></category>
            <category><![CDATA[webassembly]]></category>
            <dc:creator><![CDATA[c-bata]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 08:55:40 GMT</pubDate>
            <atom:updated>2023-10-31T08:55:40.338Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>As we announced in the <a href="https://medium.com/optuna/announcing-optuna-3-4-0087644c92fa">Optuna 3.4 release blog</a>, we have introduced Optuna Jupyter Lab extension and the VS Code extension. These extensions enable easy access to the Optuna Dashboard within Jupyter Lab and VS Code, making it convenient for you to view your optimization history, hyperparameter importances, etc. in graphs and tables.</p><p>This article aims to elaborate on the process of implementing these extensions and their functioning mechanism. Our hope is that this explanation will provide beneficial information for anyone interested in developing extensions for Jupyter Lab or VS Code.</p><p>Optuna Dashboard consists of a server program written in Bottle web framework and a single page application written in React, as shown in the following figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1K1vhBS-uNZod5R70mzRA.png" /></figure><p>To integrate the Optuna Dashboard into Jupyter Lab, several significant modifications were necessary:</p><ul><li>Adapting the Optuna Dashboard’s server, originally written in the Bottle framework, to run within Jupyter Lab.</li><li>Substituting the JavaScript HTTP client library with the @jupyterlab/services/ServerConnection.</li><li>Developing a Jupyter Lab-specific user interface (including input screens for Optuna’s storage URL, etc.).</li><li>Fixing the UI which is broken in Jupyter Lab (e.g. correcting display cut off)</li></ul><p>Though these tasks were time-consuming and demanding, this article will primarily focus on how to operate a Bottle application within Jupyter Lab. Given that Jupyter Lab employs the Tornado web framework, its extension must be implemented as a Tornado handler like <a href="https://github.com/jupyterlab/extension-examples/blob/36a65956d5385e/server-extension/jupyterlab_examples_server/handlers.py#L10-L25">this official example</a>. Consequently, running the Optuna Dashboard server within Jupyter Lab is not a straightforward endeavor.</p><p>Reimplementing all of the Optuna Dashboard server’s procedures from Bottle to Tornado would not have been a feasible solution, considering the implementation effort and subsequent maintenance costs. Therefore, we decided to invoke the processing of the Bottle application on the Tornado handler by converting the request object coming to the Tornado handler into a form comprehensible to Bottle. When we call procedures written in Bottle from the Tornado handler, there are two major options to consider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*0fpoiP9ZrfM8WCiQnqYntA.png" /></figure><ol><li>Calling WSGI entrypoint from the Tornado handler</li><li>Calling Bottle’s view functions directly from the Tornado handler</li></ol><p>In conclusion, we implemented this with the former approach. We avoided the latter approach because the request object in the Bottle framework is defined as <a href="https://github.com/bottlepy/bottle/blob/99341ff3791b2e7e705d7373e71937e9018eb081/bottle.py#L4340-L4347">a variable which is thread-local and module global</a>, and they can be imported and utilized by view functions. Invoking Bottle’s view functions from within a Tornado handler requires the initial setup of request object and response object. Compared to the former approach, the latter approach had more points to consider and was thought to be more complex.</p><p>The former approach is not overly complex given you have an understanding of the WSGI specifications (refer to <a href="https://peps.python.org/pep-0333/">PEP 333</a> and <a href="https://peps.python.org/pep-3333/">PEP 3333</a> for more information about WSGI). After converting the request object passed to the Tornado handler into a WSGI environment dictionary object, you can invoke the WSGI entrypoint. This is achieved by mapping the status code and HTTP headers set in the start_response() function and the response body obtained from the function return value to the Tornado response object. Originally, the plan was to implement these processes from scratch, but fortunately, suitable processes were already established in the <a href="https://www.tornadoweb.org/en/stable/wsgi.html">tornado.wsgi module</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*WgMFW7Tu9haP4NEdGpWp0g.png" /></figure><p>A potential concern is the fact that Tornado is an asynchronous web framework, while the WSGI application is just a function (callable object). This discrepancy may block the Tornado server’s eventloop for prolonged periods while waiting for a response from the WSGI application. If such practical issues arise, one possible workaround would be to use multi-thread to prevent the eventloop from blocking. While I have not yet conducted a detailed investigation on this, if you encounter any issues such as Jupyter Lab becoming slow while using the Optuna Dashboard extension, I would appreciate your feedback.</p><h3>VS Code Extension</h3><p>The process of Implementing the VS Code extension is more complex than that of the Jupyter Lab extension, primarily because it fundamentally relies on Node.js. Consequently, we have decided to depart from the full functionality support of the Optuna Dashboard, as executed in the Jupyter Lab extension. Our plan is to create an application that leverages WebAssembly, removing the need for a Python web server. This application will then be encapsulated using WebView and offered as a VS Code extension.</p><p>The independence from Python, coupled with the ability to run on a web browser, has made it possible to host the application on GitHub Pages. Basic functionalities such as visualizing optimization history and the importance of hyperparameters are already supported. Thus it’s ready-to-use when you need a swift review of the optimization history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*8AkLOoLucT8jT09nvVcEzA.gif" /><figcaption><a href="https://optuna.github.io/optuna-dashboard/">https://optuna.github.io/optuna-dashboard/</a></figcaption></figure><p>The most crucial responsibility of the Python web server is loading Optuna studies and trials from the storage. It poses a significant challenge to support databases like MySQL and PostgreSQL — which transmit data via a TCP connection — to run on a web browser. Consequently, the strategy for the VS Code extension was to restrict support to file-based storages such as SQLite3 and <a href="https://medium.com/optuna/distributed-optimization-via-nfs-using-optunas-new-operation-based-logging-storage-9815f9c3f932">JournalFileStorage</a>.</p><p>We utilize <a href="https://www.npmjs.com/package/@sqlite.org/sqlite-wasm">@sqlite.org/sqlite-wasm</a> for data loading from SQLite3. Optuna’s database manages the schema with the DB migration tool Alembic, and changes are made as needed through migration. Given that the table definition may vary based on the Optuna version in use, we issue suitable SQL statements depending on the schema version. This complexity in schema handling presents difficulties for utilizing solutions such as ORM. Consequently, in the VS Code extension, we assemble and issue all raw SQL.</p><p>Currently, it only supports SQLite3, but it would be possible to support <a href="https://medium.com/optuna/distributed-optimization-via-nfs-using-optunas-new-operation-based-logging-storage-9815f9c3f932">JournalFileStorage</a> by implementing a process to restore the state from operational logs saved in JSON Lines format. We might be able to prioritize this if we receive feedback through <a href="https://github.com/optuna/optuna-dashboard/issues">GitHub issues</a> or <a href="https://marketplace.visualstudio.com/items?itemName=Optuna.optuna-dashboard#overview">Visual Studio Marketplace reviews</a>. We look forward to your feedback.</p><p>Furthermore, the VS Code extension computes hyperparameter importances directly on the web browser leveraging WebAssembly. The task of implementing fANOVA (an algorithm used to calculate hyperparameter importance) from scratch is challenging due to its requirement for a random forest. Fortunately, Takeru Ohta (<a href="https://github.com/sile">@sile</a>), an Optuna committer, had already implemented <a href="https://github.com/sile/fanova">fANOVA</a> and <a href="https://github.com/sile/randomforest">random forest</a> in Rust. I prepared <a href="https://github.com/optuna/optuna-dashboard/blob/c4ac592555da9b7063564c0eb3fdb262e1b88758/rustlib/src/lib.rs#L6-L31">a JavaScript interface using wasm-bindgen</a> and utilized it in the extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9JXKGaM_VkN_y5cYbtSEIw.gif" /><figcaption>VS Code Extension</figcaption></figure><p>The current release of the VS Code extension does have some areas of implementation that could be improved upon. In future updates, we plan to focus on the following points. If you have any requests or suggestions, we welcome them via GitHub issues or pull requests.</p><ul><li>Support for <a href="https://medium.com/optuna/distributed-optimization-via-nfs-using-optunas-new-operation-based-logging-storage-9815f9c3f932">JournalFileStorage</a></li><li>Compatibility with code-server</li><li>Reflect changes in storage onto the Dashboard screen using the <a href="https://code.visualstudio.com/api/extension-guides/custom-editors">Custom Editor API</a></li><li>Perform data loading from storage on the Web Worker.</li></ul><h3>Conclusion</h3><p>In this article, we explained how the Optuna Dashboard is run within Jupyter Lab and VS Code, and the mechanism behind it. If this article has piqued your interest in the development of Optuna Dashboard, we would be delighted if you would join the development, referring to <a href="https://github.com/optuna/optuna-dashboard/blob/main/CONTRIBUTING.md">this document</a>.</p><p>In conclusion, I need to underscore that these achievements are the result of collective efforts. The development of the Jupyter Lab extension was aided by my collaboration with Shinichi Hemmi (<a href="https://github.com/Alnusjaponica">@Alnusjaponica</a>), an Optuna committer. Moreover, Yuiga Wada (<a href="https://github.com/YuigaWada">@YuigaWada</a>) contributed to supporting Optuna’s older database schema, and <a href="https://github.com/ciffelia">@ciffelia</a> contributed to enhancing error handling in the Rust program. I would like to express my gratitude for everyone’s invaluable contributions to the Optuna Dashboard.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b29da7da7b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/optuna/the-internal-of-optunas-jupyter-lab-and-vs-code-extensions-5b29da7da7b6">The Internal of Optuna’s Jupyter Lab and VS Code Extensions</a> was originally published in <a href="https://medium.com/optuna">Optuna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Announcing Optuna 3.4]]></title>
            <link>https://medium.com/optuna/announcing-optuna-3-4-0087644c92fa?source=rss-a9250c4c9905------2</link>
            <guid isPermaLink="false">https://medium.com/p/0087644c92fa</guid>
            <category><![CDATA[automl]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[human-in-the-loop]]></category>
            <category><![CDATA[optuna]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <dc:creator><![CDATA[c-bata]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 07:18:10 GMT</pubDate>
            <atom:updated>2024-08-28T14:18:21.823Z</atom:updated>
            <content:encoded><![CDATA[<p>We are pleased to announce the release of Optuna 3.4! Optuna 3.4 newly supports preferential optimization, an Optuna artifact, a Jupyter Lab extension, and a VS Code extension. This blog will walk you through these updates and explain how to use new features. Let’s take a closer look at these new and improved features.</p><h3>✨ Highlights</h3><h3>Preferential Optimization</h3><p>In this release, we added support for preferential optimization in Optuna Dashboard. This feature is useful when the objective function cannot be explicitly implemented but has to rely on human preferences. One example is hyperparameter optimization of a generative model. You provide a function that generates image/text/audio etc., and then you use Optuna Dashboard to report preferences to carry out the optimization.</p><p>The primary difference from <a href="https://optuna-dashboard.readthedocs.io/en/latest/tutorials/hitl.html">human-in-the-loop optimization</a>, which has already been supported since the last version, is whether users need to provide objective values explicitly in each trial. Explicit quantification of an objective function is often difficult for humans such as the appearance of a picture or the quality of a generated passage. On the other hand, it is surely possible to compare two of them, e.g. the quality of two pictures or generated passages. To this end, users may want to use this feature to optimize an objective function more robustly based on relative preferences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hdjkXBaEEgrlmHE-_Z2Cw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*tj8c02s-MdHnMynv0vz1mg.gif" /></figure><p>You can also manage and analyze the reported preferences through Optuna Dashboard. For details about how to use preferential optimization, please refer to <a href="https://optuna-dashboard.readthedocs.io/en/latest/tutorials/preferential-optimization.html">Preferential Optimization Tutorial</a>.</p><h3>Optuna Artifact</h3><p>The artifact module in Optuna was introduced from v3.3. In v3.4, we are enhancing this feature and releasing it with <a href="https://optuna.readthedocs.io/en/latest/tutorial/20_recipes/012_artifact_tutorial.html">an easy-to-understand tutorial</a>.</p><p>The artifact module caters to the demand to save and use relatively large-sized data, such as model snapshots in hyperparameter tuning of machine learning or the chemical structure in the black box optimization for complex chemistry, that is associated with each trial. The artifact module is easy to use and has high flexibility as it allows for an effortless switch of the backend. Here’s a simple example of its usage.</p><pre>import optuna<br><br><br># This artifact store for file systems.<br>artifact_store = optuna.artifacts.FileSystemArtifactStore(&quot;/path/to/directory&quot;)<br># You can use other artifact store for AWS S3 or Google cloud storage.<br># artifact_store = optuna.artifacts.Boto3ArtifactStore(&quot;my-bucket&quot;)<br># artifact_store = optuna.artifacts.GCSArtifactStore(&quot;my-bucket&quot;)<br><br><br>def objective(trial: optuna.Trial) -&gt; float:<br>        ... = trial.suggest_float(&quot;x&quot;, -10, 10)<br><br>        # Creating and writing an artifact.<br>        file_path = generate_example(...)  # This function returns some kind of file.<br>        artifact_id = upload_artifact(<br>            trial, file_path, artifact_store<br>        )  # The return value is the artifact ID.<br>        trial.set_user_attr(<br>            &quot;artifact_id&quot;, artifact_id<br>        )  # Save the ID in RDB so that it can be referenced later.<br>        return ...<br><br>study = optuna.create_study(study_name=&quot;test_study&quot;, storage=&quot;sqlite:///sqlite.db&quot;)<br>study.optimize(objective, n_trials=100)<br># Loading and displaying artifacts associated with the best trial.<br>best_artifact_id = study.best_trial.user_attrs.get(&quot;artifact_id&quot;)<br>with artifact_store.open_reader(best_artifact_id) as f:<br>    content = f.read().decode(&quot;utf-8&quot;)<br>    <br>print(content)</pre><h3>Jupyter Lab Extension</h3><p>We’ve launched an official JupyterLab extension for Optuna. You can run Optuna and view the evaluation results directly within the Jupyter Lab environment, eliminating the need to boot up the Optuna Dashboard separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WoMJ_udtKijZI4x-Dx21mA.gif" /></figure><p>To use the extension, install jupyterlab-optuna from <a href="https://pypi.org/project/jupyterlab-optuna/">PyPI</a>, click the tile to launch the extension, and input your Optuna’s storage url (e.g. sqlite:///db.sqlite3) in the dialog.</p><pre>$ pip install jupyterlab jupyterlab-optuna</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2x1jK3h0JI3Zv1FvZ9e-w.png" /></figure><h3>VS Code Extension</h3><p>We’ve launched an official VS Code Extension for Optuna. To use the extension, install it via <a href="https://marketplace.visualstudio.com/items?itemName=Optuna.optuna-dashboard#overview">Marketplace</a>, right-click the SQLite3 files (*.db or *.sqlite3) in the file explorer and select the “Open in Optuna Dashboard” from the dropdown menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9JXKGaM_VkN_y5cYbtSEIw.gif" /></figure><p>This extension is powered by WebAssembly. Since it relies on SQLite3 WASM and Rust rather than on Python, it solely works within your web browser as well. To use the extension in your web browser, simply open <a href="https://optuna.github.io/optuna-dashboard">https://optuna.github.io/optuna-dashboard</a> and drag-and-drop your SQLite3 file onto the page.</p><h3><strong>🚀 Other Improvements</strong></h3><h3>User-defined Distance for Categorical Parameters in TPE</h3><p>Previously, Optuna supported only integer, float, and categorical parameters. Now, we experimentally support user-defined metric space in TPESampler. You can specify a distance function between categorical choices. Here is an example code:</p><pre>import optuna<br>from optuna.samplers import TPESampler<br><br><br>def objective(trial):<br>    word = trial.suggest_categorical(&quot;word&quot;, [&quot;aaaaa&quot;, &quot;aabaa&quot;, &quot;bbaba&quot;])<br>    ...<br><br>def hamming_distance(s1, s2):<br>    return sum(c1 != c2 for c1, c2 in zip(s1, s2))<br><br>study = optuna.create_study(<br>    sampler=TPESampler(categorical_distance_func={&quot;word&quot;: hamming_distance}),<br>)<br>study.optimize(objective, n_trials=100)</pre><p>By using this feature, the sampler automatically considers the user-defined structure for efficient optimization, even if the categorical search space is large. Please also refer to the <a href="https://github.com/optuna/optuna/pull/4926">PR</a> for more details.</p><h3>Constrained Optimization Support for Visualization Functions</h3><p>We are continuing to develop features for constrained optimization. In Optuna 3.4, we have started supporting `plot_intermediate_values`, `plot_rank`, `plot_slice`, and `plot_timeline` for constrained optimization. These visualizations automatically use the constraint violation values specified in the sampler’s `constraint_func`.</p><h3>📈 Optuna Dashboard</h3><h3>User-Defined Plotly’s Figure Support</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*04eZVvLrKlmpDMxsh-OQFA.png" /></figure><p>Optuna Dashboard now supports user defined Plotly’s graph object. By using <a href="https://optuna-dashboard.readthedocs.io/en/latest/_generated/optuna_dashboard.save_plotly_graph_object.html#optuna_dashboard.save_plotly_graph_object">optuna_dashboard.save_plotly_graph_object()</a>, you can check your Plotly’s figure via Optuna Dashboard.</p><pre>from optuna_dashboard import save_plotly_graph_object<br><br>study = ...<br>figure = optuna.visualization.plot_optimization_history(study)<br>save_plotly_graph_object(study, figure)</pre><h3><strong>3D Model Viewer Support</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gvWVTTvlJ8XL4SpjHcEsGA.png" /></figure><p>Optuna Dashboard now incorporates with <a href="https://threejs.org/">Three.js</a>, enabling users to preview 3D models (*.stl and *.3dm), that are uploaded to Optuna’s ArtifactStore. This feature was added by <a href="https://github.com/hrntsm">@hrntsm</a>, one of the main contributors to Optuna Dashboard, to meet the needs to work on 3D CAD software with Optuna.. For more details, please read the blog post “<a href="https://medium.com/optuna/black-box-optimization-of-geometry-and-functionality-by-integrating-optuna-and-3d-cad-f2d2984d263e">Black-box optimization of geometry and functionality by integrating Optuna and 3D CAD</a>”.</p><h3>GitHub Sponsors</h3><p>Many people from various communities participate in the development of Optuna. To support these developers and to set up a place for developers to gather, we have decided to use GitHub Sponsors! We are looking forward to your support.<br><a href="https://github.com/sponsors/optuna">https://github.com/sponsors/optuna</a></p><h3>What’s Ahead</h3><p>In Optuna v3.4, we’ve rolled out new features such as Preferential Optimization, the JupyterLab extension, and the VS Code extension. Please note that these are still in their experimental stages, and there might be scope for enhancement in both functionalities and usability.</p><p>We aim to refine these features by incorporating user feedback. Your contribution in sharing your use cases on blogs, social media, and GitHub would be very helpful for the development of Optuna v3.5.</p><h3>Contributors</h3><p>As with any other release, this one would not have been possible without the feedback, code, and comments from many contributors.</p><p>Alnusjaponica, HideakiImamura, RuTiO2le, YuigaWada, adjeiv, c-bata, ciffelia, contramundum53, cross32768, eukaryo, g-tamaki, g-votte, gen740, hamster-86, hrntsm, hvy, keisuke-umezawa, knshnb, lucasmrdt, louis-she, moririn2528, nabenabe0928, not522, nzw0301, ryota717, semiexp, shu65, smygw72, sousu4, torotoki, toshihikoyanase, xadrianzetx</p><p>Thanks to those who have followed the projects from the very early days and those who have joined along the way.</p><h3>Next Step</h3><p>Check out the <a href="https://github.com/optuna/optuna/releases/tag/v3.4.0">release notes</a> for more information. To get the latest news from Optuna, follow us on <a href="https://twitter.com/OptunaAutoML">Twitter</a>. For feedback, please file an issue or create a pull request on <a href="https://github.com/optuna/optuna">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0087644c92fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/optuna/announcing-optuna-3-4-0087644c92fa">Announcing Optuna 3.4</a> was originally published in <a href="https://medium.com/optuna">Optuna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Announcing Optuna 3.1]]></title>
            <link>https://medium.com/optuna/announcing-optuna-3-1-7b4c5fac227c?source=rss-a9250c4c9905------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b4c5fac227c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[optuna]]></category>
            <category><![CDATA[automl]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[c-bata]]></dc:creator>
            <pubDate>Wed, 18 Jan 2023 05:48:27 GMT</pubDate>
            <atom:updated>2024-08-29T01:44:46.265Z</atom:updated>
            <content:encoded><![CDATA[<p>We are pleased to announce the release of Optuna 3.1! Along with 3.1, we are releasing new sampling algorithms, new storage backends, and lots of performance improvements. This blog will walk you through those updates and explain how the project evolved from version 3.0. Let’s take a closer look at these new and improved features.</p><p>Summary:</p><ol><li>New CMA-ES variant algorithm for mixed-integer search spaces</li><li>New file storage backend that is compatible with NFS (Network File System), allowing for scaling to multiple machines</li><li>Brand-new Redis storage backend that resolves various concurrency issues</li><li>Dask.distributed Integration for easy scaling to multiple machines</li><li>New sampling algorithm for exhaustive search</li><li>Improved performance of TPESampler’s constant_liar option</li><li>SciPy has become an optional dependency of Optuna, reducing 50% of Optuna’s import time</li><li>The new UI for Optuna Dashboard</li></ol><p>The Python versions supported by this release are 3.7–3.11.</p><h3>✨ What’s New</h3><h3><strong>CMA-ES with Margin</strong></h3><p>Optuna provides CMA-ES via <a href="https://medium.com/optuna/introduction-to-cma-es-sampler-ee68194c8f88">CmaEsSampler</a>, which is especially powerful in high-dimensional continuous spaces. However, Optuna’s default handling of discrete search spaces (e.g., FloatDistribution with step and IntDistribution) has a problem of being fixed to local solutions when the variance becomes small during optimization. <a href="https://arxiv.org/abs/2205.13482">CMA-ES with margin</a> is an algorithm to tackle this problem by introducing a lower bound on the marginal distribution of each discrete space.</p><p>We took a <a href="https://github.com/CyberAgentAILab/cmaes/pull/121#issuecomment-1296691448">benchmark</a> of CMA-ES with margin on HPO-bench problems and confirmed that it outperforms the original CMA-ES significantly when the number of trials is large (400–600+). Now, this feature can be easily enabled by specifying the with_margin=True argument. If you use CMA-ES for problems including discrete search spaces, please try it out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AbvDxYIGaUapm6wEXNeVzA.png" /></figure><p>See <a href="https://github.com/optuna/optuna/pull/4016">#4016</a> for details.</p><h3><strong>Distributed Optimization via NFS (Network File System)</strong></h3><p>JournalStorage is a new operation-based logging storage. Unlike conventional storages, which store the “values”, JournalStorage stores the “operation logs”. This storage allows developers to implement custom storage backends with simpler APIs.</p><p>We have introduced JournalFileStorage, a new storage backend for file systems. It can be used on NFS, allowing Optuna programs to scale to multiple machines. This can be especially useful for users who want to use Optuna in environments where it is difficult to set up database servers such as MySQL, PostgreSQL or Redis, which is otherwise often required for distributed optimization (e.g. <a href="https://github.com/optuna/optuna/issues/815">#815</a>, <a href="https://github.com/optuna/optuna/issues/1300">#1330</a>, <a href="https://github.com/optuna/optuna/issues/1457">#1457</a> and <a href="https://github.com/optuna/optuna/issues/2216#issuecomment-764792598">#2216</a>).</p><pre>import optuna<br>from optuna.storages import JournalStorage, JournalFileStorage<br><br>def objective(trial):<br>    x = trial.suggest_float(&quot;x&quot;, -100, 100)<br>    y = trial.suggest_float(&quot;y&quot;, -100, 100)<br>    return x**2 + y<br> <br>storage = JournalStorage(JournalFileStorage(&quot;./journal.log&quot;))<br>study = optuna.create_study(storage=storage)<br>study.optimize(objective)</pre><h3><strong>A Brand-New Redis Storage</strong></h3><p><a href="https://redis.io/">Redis</a> is a widely used open source software as an in-memory data store, and Optuna provided RedisStorage for tight integration with Redis. This was introduced in v1.4.0, but remained an experimental feature due to lack of performance, applicability validation and several bugs in parallel execution.</p><p>We have removed the existing RedisStorage and introduced a brand-new Redis backend storage JournalRedisStorage in this release. JournalRedisStorage is one of the JournalStorage backends introduced with this release, and is easy to use, simpler than RedisStorage, and powerful enough to work well in distributed environments.</p><p>The following is a brief description of how to use it; as long as you have a Redis server, you can use it in exactly the same way as you would use regular storage. See <a href="https://github.com/optuna/optuna/pull/4086">#4086</a> and <a href="https://github.com/optuna/optuna/pull/4102">#4102</a> for more information.</p><pre>import optuna<br>from optuna.storages import JournalStorage, JournalRedisStorage<br><br>def objective(trial):<br>    x = trial.suggest_float(&quot;x&quot;, -100, 100)<br>    y = trial.suggest_float(&quot;y&quot;, -100, 100)<br>    return x**2 + y<br> <br>storage = JournalStorage(JournalRedisStorage(&quot;redis://localhost:6379&quot;))<br>study = optuna.create_study(storage=storage)<br>study.optimize(objective)</pre><h3><strong>Dask.distributed Integration &amp; Enhanced Concurrency Support</strong></h3><p><strong>Enhanced Multi-threading Support<br></strong>The concurrency support in Optuna is greatly improved for developers who are familiar with the <a href="https://docs.python.org/3/library/concurrent.futures.html">concurrent.futures</a> module. In previous versions, you could only use the n_jobs=&lt;int&gt; option to call study.optimize in multiple threads (e.g. study.optimize(objective, …, n_jobs=5) ). From v3.1, you can also use <a href="https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor">ThreadPoolExecutor</a> as follows:</p><pre>import optuna<br>from concurrent.futures import ThreadPoolExecutor<br><br>def objective(trial):<br>    x = trial.suggest_float(&quot;x&quot;, -100, 100)<br>    y = trial.suggest_float(&quot;y&quot;, -100, 100)<br>    return x**2 + y<br><br>study = optuna.create_study()<br>with ThreadPoolExecutor(max_workers=5) as pool:<br>    for i in range(5):<br>        pool.submit(study.optimize, objective, n_trials=10)<br>print(f&quot;Best params: {study.best_params}&quot;)</pre><p><strong>Dask.distributed Integration<br></strong>DaskStorage, a new storage backend based on <a href="https://distributed.dask.org/en/stable/">Dask.distributed</a>, is supported. It allows you to leverage distributed capabilities in similar APIs with <a href="https://docs.python.org/3/library/concurrent.futures.html">concurrent.futures</a>. DaskStorage can be used with InMemoryStorage, so you don’t need to set up a database server. Here’s a code example showing how to use DaskStorage:</p><pre>import optuna<br>from optuna.storages import InMemoryStorage<br>from optuna.integration import DaskStorage<br>from distributed import Client, wait<br><br>def objective(trial):<br>    ...<br><br>with Client(&quot;192.168.1.8:8686&quot;) as client:<br>    study = optuna.create_study(storage=DaskStorage(InMemoryStorage()))<br>    futures = [<br>        client.submit(study.optimize, objective, n_trials=10, pure=False)<br>        for i in range(10)<br>    ]<br>    wait(futures)<br>    print(f&quot;Best params: {study.best_params}&quot;)</pre><p>Setting up a Dask cluster is easy: install dask and distributed, then run the dask scheduler and dask worker commands, as detailed in the <a href="https://distributed.dask.org/en/stable/quickstart.html">Quick Start Guide</a> in the Dask.distributed documentation.</p><pre>$ pip install dask distributed<br><br>$ dask scheduler<br>INFO - Scheduler at: tcp://192.168.1.8:8686<br>INFO - Dashboard at:                  :8687<br>…<br><br>$ dask worker tcp://192.168.1.8:8686<br>$ dask worker tcp://192.168.1.8:8686<br>$ dask worker tcp://192.168.1.8:8686</pre><p>See <a href="https://optuna.readthedocs.io/en/latest/reference/generated/optuna.integration.DaskStorage.html">the documentation</a> for more information.</p><h3>BruteForceSampler</h3><p>BruteForceSampler, a new sampler for brute-force search, tries all combinations of parameters. In contrast to GridSampler, this sampler does not require any additional arguments and can handle conditional search spaces. It constructs the search space in the define-by-run style while processing the objective function. BruteForceSampler tries combinations in random order and also works with parallel optimization. To use this sampler, the search space must be discrete, i.e., suggest_float with step=None is not allowed.</p><pre>import optuna<br><br>def objective(trial):<br>    c = trial.suggest_categorical(&quot;c&quot;, [&quot;float&quot;, &quot;int&quot;])<br>    if c == &quot;float&quot;:<br>        return trial.suggest_float(&quot;x&quot;, 1, 3, step=0.5)<br>    elif c == &quot;int&quot;:<br>        a = trial.suggest_int(&quot;a&quot;, 1, 3)<br>        b = trial.suggest_int(&quot;b&quot;, a, 3)<br>        return a + b<br><br>study = optuna.create_study(sampler=optuna.samplers.BruteForceSampler())<br>study.optimize(objective)</pre><p>See the <a href="https://optuna.readthedocs.io/en/v3.1.0/reference/samplers/generated/optuna.samplers.BruteForceSampler.html">document</a> for more information.</p><h3>🚀 Other Improvements</h3><h3>Bug Fix for TPE’s constant_liar Option</h3><p>The constant_liar option in the TPESampler promotes exploration in distributed optimization by adding all running trials to the “above” split of the TPE algorithm. However, there was a bug in the TPE logic that counted running trials in the population to be classified into the below/above splits. Under certain conditions, this caused some running trials or some finished trials that returned early to be unconditionally classified into the “below” split, which led to performance degradation in early trials.</p><p>We have fixed this bug and have confirmed that it improves the constant_liar performance on HPOBench. For more information and performance benchmarks, please see <a href="https://github.com/optuna/optuna/pull/4073">#4073</a>.</p><h3>Make SciPy Dependency Optional</h3><p>50% time of import optuna is consumed by SciPy-related modules. Also, it consumes <a href="https://github.com/optuna/optuna/issues/3035#issuecomment-1041023987">110MB of storage space</a>, which is really problematic in environments with limited resources such as serverless computing.</p><p>We decided to implement scientific functions on our own to make the SciPy dependency optional. Thanks to contributors’ effort on performance optimization, our implementation is as fast as the code with SciPy although ours is written in pure Python. See <a href="https://github.com/optuna/optuna/pull/4105">#4105</a> for more information.</p><p>Note that QMCSampler still depends on SciPy. If you use QMCSampler, please explicitly specify SciPy as your dependency.</p><h3>The New UI for Optuna Dashboard</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7GOSJreVlW7G0jyLsnk0hg.png" /><figcaption>The new UI for Optuna Dashboard</figcaption></figure><p>We are developing a new UI for <a href="https://github.com/optuna/optuna-dashboard">Optuna Dashboard</a> that is available as an opt-in feature from the beta release — simply launch the dashboard as usual and click the link to the new UI. Please try it out and share your thoughts with us.</p><pre>$ pip install &quot;optuna-dashboard&gt;=0.9.0b2&quot;</pre><p><a href="https://github.com/optuna/optuna-dashboard/discussions/332">Feedback Survey: The New UI for Optuna Dashboard</a></p><h3>What’s Ahead</h3><p>While we initially planned three main development targets in <a href="https://github.com/optuna/optuna/discussions/4064">Optuna v3.1 Roadmap</a>, we ended up with more than what was anticipated. Several storages and performance improvements described above were not on the roadmap initially but were developed by the growing share of contributors.</p><p>Main development targets for the upcoming Optuna v3.2 are still in the planning stages. We continually review what features to include and listen to community inputs on new areas where Optuna can help. You are welcome to submit feature requests on GitHub issues.</p><h3>Contributors</h3><p>As with any other release, this one would not have been possible without the feedback, code, and comments from many contributors.</p><p>@Abelarm, @Alnusjaponica, @ConnorBaker, @Hakuyume, @HideakiImamura, @Jasha10, @amylase, @belldandyxtq, @c-bata, @contramundum53, @cross32768, @erentknn, @eukaryo, @g-votte, @gasin, @gen740, @gonzaload, @halucinor, @himkt, @hrntsm, @hvy, @jmsykes83, @jpbianchi, @jrbourbeau, @keisuke-umezawa, @knshnb, @mist714, @ncclementi, @not522, @nzw0301, @rene-rex, @reyoung, @semiexp, @shu65, @sile, @toshihikoyanase, @wattlebirdaz, @xadrianzetx, @zaburo-ch</p><p>Thanks to those who have followed the projects from the very early days and those who have joined along the way.</p><h3>Next Step</h3><p>Check out the <a href="https://github.com/optuna/optuna/releases/tag/v3.1.0">release notes</a> for more information. To get the latest news from Optuna, follow us on <a href="https://twitter.com/OptunaAutoML">Twitter</a>. For feedback, please file an issue or create a pull request on <a href="https://github.com/optuna/optuna">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b4c5fac227c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/optuna/announcing-optuna-3-1-7b4c5fac227c">Announcing Optuna 3.1</a> was originally published in <a href="https://medium.com/optuna">Optuna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to the Implementation of Optuna, a Hyperparameter Optimization Framework]]></title>
            <link>https://medium.com/optuna/an-introduction-to-the-implementation-of-optuna-a-hyperparameter-optimization-framework-33995d9ec354?source=rss-a9250c4c9905------2</link>
            <guid isPermaLink="false">https://medium.com/p/33995d9ec354</guid>
            <category><![CDATA[optuna]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[c-bata]]></dc:creator>
            <pubDate>Thu, 18 Nov 2021 00:39:03 GMT</pubDate>
            <atom:updated>2024-08-29T01:57:20.031Z</atom:updated>
            <content:encoded><![CDATA[<p>I am Masashi Shibata from the CyberAgent AI Lab (GitHub: <a href="https://github.com/c-bata">@c-bata</a>).</p><p>Hyperparameter optimization is one of the most important processes for a machine learning model to deliver high performance. Optuna [1] is a popular Python library for hyperparameter optimization, and is an easy-to-use and well-designed software that supports a variety of optimization algorithms. This article describes the internal implementations of Optuna, with a main focus on the software aspects.</p><p>In order to understand the internal implementations of Optuna, you need to know the roles of the major components and the overall flow of the execution. However, with Optuna actively being developed and the amount of code growing, it has become difficult to get a hold of the overall flow from reading the code. So, I created a tiny program called Minituna. Minituna has three versions with each having 100, 200, and 300 lines of code. The final version is a small program of only about 300 lines, but with a practical pruning algorithm, it is quite authentic.</p><blockquote>Minituna: A toy hyperparameter optimization framework intended for understanding Optuna’s internal design.<br><a href="https://github.com/CyberAgentAILab/minituna">https://github.com/CyberAgentAILab/minituna</a></blockquote><p>I have created each version of Minituna with the intention of helping you to understand how Optuna is designed in three steps:</p><ol><li>Understand the main components of Optuna and how they are called</li><li>Understand how to use categorical, integer, and loguniform</li><li>Understand the pruning API and the median stopping rule algorithm</li></ol><p>I encourage you to practice reading the Minituna code by typing out its entire code. Once you get a good understanding of how Minituna is designed, it will not be too difficult to read the Optuna code. This article will not cover the simple facts that you can easily read from the Minituna code. Instead, I will try to provide some tips to help you in reading and practicing with the Minituna code, as well as to explain the differences between Minituna and Optuna.</p><p>Note that Minituna was implemented based on the Optuna v2.1.0 code. Since v2.4.0 (<a href="https://github.com/optuna/optuna/releases/tag/v2.4.0">https://github.com/optuna/optuna/releases/tag/v2.4.0</a>), Optuna has a new interface that can pass multiple objective values in order to support multi-objective optimization. The design has not changed significantly, but you should keep this in mind when reading the Optuna code.</p><h3>minituna_v1: The Roles of Trial, Study, Sampler, and Storage and How They Are Called</h3><p>Minituna v1 is a very small program of about 100 lines. But, the main components have already been implemented in it, and you can run a program like the following. Please note that all the examples presented in this article are compatible with Optuna and will run without problems even if you replace the import statement with <strong>import optuna as minituna</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d7076e9d6d4f1cd4ad6a498a0f37c3b/href">https://medium.com/media/9d7076e9d6d4f1cd4ad6a498a0f37c3b/href</a></iframe><p>This is how we define the objective function in Optuna. The objective function takes the trial object and returns the objective value. In this example, the objective function is called 10 times, and the best value it has obtained out of 10 trials (we assume a minimization problem here) and the parameters are printed.</p><p>Now let us read the minituna_v1 code. There are five classes defined in minituna_v1, and these key components appear frequently in the Optuna code as well. Take a look at the code to see what each class does and how it is called.</p><ul><li><strong>Study: A component that manages information about a given optimization task<br></strong>For a given optimization task, the study component manages all the information such as which algorithm to use (Sampler) and where to store the trial results (Storage). They are specified as arguments in the <strong>create_study()</strong> function.</li><li><strong>Trial: A component that corresponds to each trial<br></strong>The objective function samples parameters from Optuna via the API provided by the trial object, and reports intermediate values to perform pruning.</li><li><strong>Storage: A component that stores the results of optimization trials.<br></strong>Thanks to this component, Optuna is able to support RDB storages, enabling persistence of trial results and distributed optimization.</li><li><strong>FrozenTrial: A representation of each trial on the storage layer<br></strong>This component holds the objective value and the parameters used to evaluate the objective function in each trial. For example, when using RDB storages, the information retrieved from the DB by SQL is put into the FrozenTrial object.</li><li><strong>Sampler: A component to implement an algorithm to select the next parameter to evaluate<br></strong>This component implements an algorithm to find out which parameters should be evaluated in order to get a better objective value. The sampling of hyperparameters with Bayesian optimization or evolution strategies is defined in the sampler component. For simplicity of explanation, I have implemented only random sampling in Minituna. This article does not cover the details of the Bayesian optimization and evolution strategies supported by Optuna.</li></ul><h3>minituna_v2: How to Use Categorical, Integer, and LogUniform</h3><p>minituna_v2 supports the following suggest APIs in addition to <strong>suggest_uniform()</strong> (samples of real parameters from a uniform distribution).</p><ul><li><strong>suggest_categorical(name, choices=[...])</strong>: Samples categorical parameters</li><li><strong>suggest_int(name, low, high)</strong> : Samples integer parameters</li><li><strong>suggest_loguniform(name, low, high)</strong> : Samples real parameters from the space in logarithmic scale</li></ul><p>This allows us to optimize the objective function like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/488762096ee3cca84dc34e70c7529e0d/href">https://medium.com/media/488762096ee3cca84dc34e70c7529e0d/href</a></iframe><p>The key to understanding the minituna_v2 code is that all parameters are represented as floats inside the storage. In the previous example, the categorical parameters are strings such as “SVC” and “RandomForest”, but even these are represented as floats. For this, we introduce the following abstract base class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3701ac4c81218619f6f20cc7bf1537f7/href">https://medium.com/media/3701ac4c81218619f6f20cc7bf1537f7/href</a></iframe><p>Each parameter has two representations: internal_repr and external_repr. internal_repr is a parameter representation inside the storage and is a float value. <em>external_repr</em> is a representation that is actually used by the objective function, so it can be a string, integer, or anything. To help you understand, I encourage you to try it out.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ca04c650c1a74b6db427b2509260139/href">https://medium.com/media/6ca04c650c1a74b6db427b2509260139/href</a></iframe><p>The distribution object is needed for the conversion between internal_repr and external_repr. Therefore, the distribution object is also saved in the storage. That is the reason why the distributions field has been added to FrozenTrial.</p><p>There are several differences between Minituna and Optuna in terms of the suggest API.</p><ol><li>Optuna has <strong>DiscreteUniformDistribution </strong>and <strong>IntLogUniformDistribution</strong>. <strong>DiscreteUniformDistribution</strong> is essentially the same as <strong>IntLogUniformDistribution</strong> with the only difference being the range of discretization. <strong>IntLogUniformDistribution</strong> is no more than adding the same kind of functionality as <strong>LogUniformDistribution</strong> to <strong>IntUniformDistribution. </strong>Therefore, you will be able to read Optuna easily if you practice reading the minituna_v2 code. <em>(* Update in Nov. 2021: Please note that two additional distributions, </em><strong>FloatDistribution</strong><em> and </em><strong>IntDistribution</strong><em> have recently been introduced. See </em><a href="https://github.com/optuna/optuna/pull/3063"><em>https://github.com/optuna/optuna/pull/3063 </em></a><em>for more details.)</em></li><li>Optuna provides an API called <strong>suggest_float(name, low, high, step=None, log=False)</strong>, which was added because the word “uniform” in <strong>suggest_uniform(name, low, high)</strong> and <strong>suggest_loguniform(name, low, high)</strong> is a little confusing, and also for consistency with <strong>suggest_int</strong>. Now that <strong>suggest_float</strong>has been formally adopted, <strong>suggest_uniform</strong>, <strong>suggest_loguniform</strong>, and <strong>suggest_discrete_uniform</strong> could be deprecated, but the discussion on this topic has not progressed. <em>(* Update in Nov. 2021: The consistency of suggest APIs is being discussed in </em><a href="https://github.com/optuna/optuna/issues/2939"><em>https://github.com/optuna/optuna/issues/2939</em></a><em> and will be improved in Optuna V3.)</em></li><li>To put the distribution into RDBStorage or RedisStorage, you need to serialize it into some format. In Optuna, it is serialized into JSON and then stored. This means that the possible categorical parameter types are limited to JSON serializable objects, such as <strong>CategoricalChoiceType = Union[None, bool, int, float, str]</strong>.</li></ol><h3>Understand the Storage Layer Properly</h3><p>If you have read the codes all the way to minituna_v2, you can start reading the Optuna code. Next, I will give a brief introduction to the storage layer before going into the details of minituna_v3.</p><p>When I started reading Optuna’s source code, the first thing I did was to get a good understanding of the storage layer. This is because if you understand what kind of information is in the storage, you can easily imagine what Optuna needs to do in order to implement each function. You can also roughly figure out the design differences between Minituna and Optuna by reading the code of the storage layer. To better understand the storage layer, I recommend checking out the <a href="https://github.com/optuna/optuna/blob/v2.0.0/optuna/storages/_rdb/models.py">SQLAlchemy model definition</a> for RDBStorage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05a604b2c74e2167cb1201e39ccc1b9e/href">https://medium.com/media/05a604b2c74e2167cb1201e39ccc1b9e/href</a></iframe><p>Here are a few extra things to keep in mind when you read the code in the storage layer:</p><ul><li>To keep the code simple, Minituna’s storage can only hold information about one study while Optuna’s code supports multiple studies.</li><li>Since Optuna supports multiple studies, the trial_id field in TrialModel does not always rise incrementally within the study. So, the number field was added to Optuna because it is useful to have an identifier that simply goes up like 1, 2, 3, and so on within the study in order to implement an algorithm.</li><li>TrialState has two states: PRUNED and WAITING. The former was added to implement the pruning function which will be explained later in the minituna_v3 section, and the latter was added to implement the <strong>enqueue_trial()</strong> function.</li></ul><h3>minituna_v3: Pruning by Median Stopping Rule</h3><p>minituna_v3 is a program of about 300 lines. It supports pruning (early stopping). Pruning is not a feature that all Optuna users use, so you do not have to understand it unless you are interested.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/369aeb5223cdfb6e03c74903c8af4f1c/href">https://medium.com/media/369aeb5223cdfb6e03c74903c8af4f1c/href</a></iframe><p>You only need two APIs to use the pruning function.</p><ol><li><strong>trial.report(value, step)</strong> to save intermediate values in the storage.</li><li>If <strong>trial.shoud_prune()</strong> is true, raise a <strong>TrialPruned()</strong> exception and stop the learning process.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B7kr3r_JJRL9rSQlRbBtHg.jpeg" /><figcaption>Optuna Trial API design (Source: Figure.6 in the Optuna research paper [1])</figcaption></figure><p>As you can see from this API, all the pruning algorithms currently supported by Optuna decide whether to prune or not based on the intermediate values. In Minituna, I have implemented an algorithm called Median Stopping Rule [2]. Fortunately, none of the pruning algorithms supported by Optuna are that complex.</p><p>All these algorithms allow terminating the learning process prematurely based on the empirical knowledge that if the intermediate value is low, the final value will not be that good either, in order to save time. In addition to the median stopping rule, which I will describe below, Optuna also supports algorithms such as Successive Halving [3, 4] and Hyperband [5], but the basic ideas remain largely the same.</p><p>The median stopping rule basically trims away the lower half (the ones worse than the median value of the previous trial’s intermediate values) at each step. The following figure illustrates how the median stopping rule works. Since the code is simple, reading it together with the following figure should give you a good idea of how the median stopping rule works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZyY7GfILSF5jg2Eeodv6wA.jpeg" /><figcaption>How the median stopping rule works</figcaption></figure><p>If you would like to read the implementations of SuccessiveHalving and Hyperband in Optuna, there is one thing worth keeping in mind. Because Optuna is not designed to suspend or resume a particular trial, its algorithm has been slightly modified, and behaves differently from the algorithm described in the paper. To learn more about Optuna’s implementation of Successive Halving, please read Algorithm 1 in Optuna’s paper [1]. For Hyperband, please read the blog article “<a href="https://medium.com/optuna/optuna-supports-hyperband-93b0cae1a137">How We Implement Hyperband in Optuna</a>” posted by crcrpar who implemented Hyperband.</p><p>I will also touch on an issue related to the design of Pruner. As you can see from Minituna’s source code, the Pruner and Sampler interfaces are clearly separated in Optuna. This gives Optuna’s code good clarity and allows us to easily switch between Sampler and Pruner and use them in any combination. This is a great advantage.</p><p>On the other hand, some algorithms require Pruner and Sampler to work together closely, which cannot be implemented in the current design. In fact, a little trick was used in the background to implement Hyperband in order to make Pruner and Sampler work together. There is still room for discussion about the interfaces of Pruner and Sampler. If you have read the code and come up with some ideas for improvement, I would appreciate your suggestions.</p><h3>How Joint Sampling Works in the Define-by-Run Interface</h3><p>I will also describe Joint Sampling, which was not covered in Minituna due to the limited size of the implementation. This mechanism is unique to Optuna, which uses the Define-by-Run interface. To implement optimization algorithms such as <strong>SkoptSampler</strong>(GP-BO) and <strong>CmaEsSampler</strong>, which consider dependencies between parameters, you need to understand the concept of Joint Sampling. If you are doing research on Bayesian optimization or evolution strategies, you should be able to implement your own Sampler on Optuna once you become familiar with Joint Sampling.</p><p>The design of Minituna’s Sampler interface is almost identical to that of Optuna’ s when it was v0.12.0. However, the interfaces in Optuna v0.13.0 and later versions are different from those. You can see the difference by comparing the following Sampler interfaces.</p><ul><li>v0.12.0: <a href="https://github.com/optuna/optuna/blob/v0.12.0/optuna/samplers/base.py">optuna/samplers/base.py</a></li><li>v2.0.0: <a href="https://github.com/optuna/optuna/blob/v2.0.0/optuna/samplers/_base.py">optuna/samplers/_base.py</a></li></ul><p>To gain a better understanding of Joint Sampling, let us take a look at some examples and see what the search space looks like for each of the objective functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f67be0c65f1ddc8f66153940186847a/href">https://medium.com/media/9f67be0c65f1ddc8f66153940186847a/href</a></iframe><p>The search space of this objective function will always be like the one below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5567bde76c85fe6a9755ed40528fa21/href">https://medium.com/media/d5567bde76c85fe6a9755ed40528fa21/href</a></iframe><p>Now, what about the search space of the following objective function?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4909c39df60d2d83265d5c4aab0b674f/href">https://medium.com/media/4909c39df60d2d83265d5c4aab0b674f/href</a></iframe><p>In the Define-by-Run interface, the search space is determined at runtime. This example has more than one search space because there is a conditional <em>if</em> statement in the search space. It switches between the following two search spaces depending on the context.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0274d9fc309dde013379b3a0f92b237b/href">https://medium.com/media/0274d9fc309dde013379b3a0f92b237b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a56ae1895a03138ffa983e46af0ca323/href">https://medium.com/media/a56ae1895a03138ffa983e46af0ca323/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*df2QdNE9rY_E8ySQmCmKbw.jpeg" /><figcaption>The flow diagram of calling the Sampler methods (Source: <a href="https://optuna.readthedocs.io/en/latest/reference/generated/optuna.samplers.BaseSampler.html">Optuna official document</a>)</figcaption></figure><p><strong>CmaEsSampler</strong> and <strong>SkoptSampler</strong> will then extract the ones that appear across all search spaces using the <strong>Sampler.infer_relative_search_space(study, trial)</strong> method and pass them as the third argument to <strong>Sampler.sample_relative(study, trial, search_space).</strong> In other words, only the classifier parameter is treated as a joint search space in the above example. GP-BO and CMA-ES are used only for samples from this joint search space, which is called Joint Sampling. Here is a diagram of how the Joint Sampling works.</p><p><strong>svc_c</strong>, <strong>rf_max_depth</strong>, and other parameters that are not included in the joint search space will fallback to Samplers where the method does not consider dependencies between variables, such as <strong>RandomSampler</strong> and <strong>TPESampler</strong>.</p><h3>Summary</h3><p>This article introduced Minituna and provided some additional tips on how to read through the Minituna and Optuna codes. If you have practiced reading the Minituna code by typing out all its code up to Minituna v2 and have a good grasp of the whole process now, you should be able to read the Optuna code. I would recommend that you start with the component that interests you the most. Also, the Optuna development team is very supportive, and they give detailed PR reviews. I hope this article will encourage you to join us in the development of Optuna in the future.</p><h3>References</h3><ol><li>T. Akiba, S. Sano, T. Yanase, T. Ohta, and M. Koyama: Optuna: A Next-generation Hyperparameter Optimization Framework. In Proceedings of the 25th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, pp. 2623–2631, 2019.</li><li>D. Golovin, B. Sonik, S. Moitra, G. Kochanski, J. Karro, and D.Sculley: Google Vizier: A Service for Black-Box Optimization. In Proceedings of the 23rd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, pp. 1487–1495, 2017.</li><li>K. Jamieson and A.Talwalkar: Non-stochastic Best Arm Identification and Hyperparameter Optimization. In Proceedings of the 19th International Conference on Artificial Intelligence and Statistics (AISTATS), PMLR 51:240–248, 2016.</li><li>L. Li, K. Jamieson, A. Rostamizadeh, E. Gonina, J. Ben-tzur, M. Hardt, B. Recht, and A. Talwalkar. A System for Massively Parallel Hyperparameter Tuning. Proceedings of Machine Learning and Systems, 2:230–246, 2020.</li><li>L. Li, K. Jamieson, G. DeSalvo, A. Rostamizadeh and A. Talwalkar: Hyperband: A Novel Bandit-Based Approach to Hyperparameter Optimization. Journal of Machine Learning Research, 18, pp. 1–52, 2017.</li></ol><h3>Acknowledgments</h3><p>I would like to thank the Optuna development team and Mr. Saito of SkillUp AI for reviewing this article.</p><p>—</p><p><em>This article is a translation of </em><a href="https://cyberagent.ai/optuna-from-scratch"><em>the Japanese blog post</em></a><em> of CyberAgent AI tech studio.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33995d9ec354" width="1" height="1" alt=""><hr><p><a href="https://medium.com/optuna/an-introduction-to-the-implementation-of-optuna-a-hyperparameter-optimization-framework-33995d9ec354">An Introduction to the Implementation of Optuna, a Hyperparameter Optimization Framework</a> was originally published in <a href="https://medium.com/optuna">Optuna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to CMA-ES sampler.]]></title>
            <link>https://medium.com/optuna/introduction-to-cma-es-sampler-ee68194c8f88?source=rss-a9250c4c9905------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee68194c8f88</guid>
            <category><![CDATA[optuna]]></category>
            <category><![CDATA[cma-es]]></category>
            <dc:creator><![CDATA[c-bata]]></dc:creator>
            <pubDate>Wed, 10 Mar 2021 06:09:26 GMT</pubDate>
            <atom:updated>2024-08-29T02:03:06.667Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to CMA-ES Based Sampler</h3><p>Hi, I’m <a href="https://github.com/c-bata">@c-bata</a>, an author of <a href="https://github.com/CyberAgentAILab/cmaes">cmaes</a> library. Optuna uses a univariate TPE for single objective optimization by default, but you can easily switch to other samplers.</p><p>In this article, I introduce <a href="https://optuna.readthedocs.io/en/stable/reference/generated/optuna.samplers.CmaEsSampler.html"><em>CmaEsSampler</em></a>. It may perform better than Optuna’s default sampler. After reading this article, you will know the followings:</p><ul><li>What is CMA-ES?</li><li>How to use <em>CmaEsSampler</em>.</li><li>The variants of CMA-ES.</li><li>When you should NOT use <em>CmaEsSampler</em>.</li></ul><h3>What is CMA-ES?</h3><p>Covariance Matrix Adaptation Evolution Strategy (CMA-ES) [1] is one of the most promising methods for black-box optimization, where objective functions cannot be described using an explicit representation in general. CMA-ES has shown the best performance out of over 100 black-box optimization methods for various benchmark problems [2].</p><p>CMA-ES samples solutions (i.e., solutions correspond to hyperparameters if you perform hyperparameter optimization) from a multivariate gaussian distribution. After evaluating all solutions, the solutions are sorted by evaluation values, then updating the distribution parameters (i.e., the mean vector and the covariance matrix) based on the ranking of evaluation values. The following animation explains the behavior of CMA-ES.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Tlq6-6hY9U9Ltxjp6kdVdg.gif" /><figcaption>Left, the optimal solutions (yellow stars) and the solutions sampled by CMA-ES (red points); Right, the update process of the multivariate gaussian distribution.</figcaption></figure><p><a href="https://optuna.readthedocs.io/en/stable/reference/generated/optuna.samplers.CmaEsSampler.html"><em>CmaEsSampler</em></a> is added at v1.3.0 and stabled at v2.0.0. This sampler uses <a href="https://github.com/CyberAgentAILab/cmaes">cmaes</a> under the hood. The usage is like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43e1911337bb091a5e1ffafc81fa800f/href">https://medium.com/media/43e1911337bb091a5e1ffafc81fa800f/href</a></iframe><p>The only thing you need to know when using <em>CmaEsSampler</em> is to pass the object via <em>sampler</em> argument. I think this is enough for almost objective functions, but <em>CmaEsSampler</em> provides a lot of options for more efficient optimization.</p><h3>Warm Starting CMA-ES</h3><p>Warm Starting CMA-ES (WS-CMA-ES) [3] significantly improves the optimization performance by transferring the optimization results of similar HPO tasks as prior knowledge. This algorithm is proposed by <a href="https://github.com/nmasahiro">@nmasahiro</a>, a co-maintainer of cmaes library, and accepted at AAAI 2021.</p><p>Warm Starting CMA-ES is a very powerful technique when you are in the following situations:</p><ul><li>You have an optimization history of your objective functions with a subset of the dataset (e.g. a history of training your model with 10% of a full dataset).</li><li>You have an optimization history of your objective functions with different dataset.</li><li>Your system runs hyperparameter optimization weekly or monthly. In this case, you can use the previous optimization history to perform optimization for the next week/month.</li></ul><p>Here is the result of an experiment to optimize hyperparameters of LightGBM for Kaggle’s Toxic Comment Classification Challenge data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Xq2zIQwUbhv-12_LYU3EPg.png" /><figcaption>An experiment with warm starting optimization using a result of the HPO for a subset of the dataset. The horizontal axis represents the number of evaluations. Source code is available at GitHub (URL: <a href="https://github.com/c-bata/benchmark-warm-starting-cmaes">https://github.com/c-bata/benchmark-warm-starting-cmaes</a>)</figcaption></figure><p>In this experiment, we use 10% of the full dataset as the source task. The usage of Warm Starting CMA-ES is like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/775dd041647aba70e601744a70d1a836/href">https://medium.com/media/775dd041647aba70e601744a70d1a836/href</a></iframe><p>Please see the line to generate a sampler object with `source_trials` option. To transfer the similar HPO tasks, you just pass the list of FrozenTrials of the source task.</p><h3>Restarting Strategy for CMA-ES</h3><p>IPOP-CMA-ES (“IPOP” is a short of “Increasing POPulation size”) [4] is a method to restart CMA-ES with increasing population size when CMA-ES converges to a local minimum. By increasing the population size, the search characteristic becomes more global after each restart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*v89GCn5-NX_qhP0Hc0bGZw.gif" /><figcaption>CMA-ES is restarted when converges to a local minimum.</figcaption></figure><p>This algorithm is useful when there are a lot of evaluation budgets and expected to have multiple local minimums. The usage is like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1698f789419f1fcbb65ac70dbe35d5a/href">https://medium.com/media/f1698f789419f1fcbb65ac70dbe35d5a/href</a></iframe><p>To use IPOP-CMA-ES, you need to set <em>restart_strategy=”ipop”</em>. There is an additional parameter <em>inc_popsize</em> (default: 2) which is a multiplier for increasing population size before each restart. According to the paper, it reveals similar performance for factors between 2 and 3.</p><h3>Separable CMA-ES</h3><p>Separable CMA-ES (sep-CMA-ES) [5] is an algorithm which constrains the covariance matrix to be diagonal. Because the model complexity is reduced, the learning rate for the covariance matrix can be increased. Consequently, this algorithm outperforms CMA-ES if hyperparameters are not correlated. Here is the benchmark result on the six-hump camel function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*89DtjQ0SggejSCJ-HF_7Ig.png" /></figure><p>As this benchmark result shows, sep-CMA-ES outperforms CMA-ES algorithm especially on a small budget. The usage is like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11bc99f04c9cb28b4085f8ac42cbecfe/href">https://medium.com/media/11bc99f04c9cb28b4085f8ac42cbecfe/href</a></iframe><p>To use sep-CMA-ES, you need to enable a <em>use_separable_cma</em> option. Please note that it is prohibited to use a <em>solution_trials</em> option together since <em>CmaEsSampler</em> currently does not support a warm starting method for sep-CMA-ES.</p><h3>When you should NOT use CmaEsSampler.</h3><p>With the moderate evaluation budget, CMA-ES achieves attractive performance for continuous optimization. However, <em>CmaEsSampler</em> does not necessarily outperform bayesian optimization methods in the following cases:</p><ul><li><strong>Categorical parameter:</strong> <em>CmaEsSampler</em> does not support categorical parameters. So I recommend you to use <em>TPESampler</em> or <em>SkoptSampler</em> instead if your search space contains categorical parameters.</li><li><strong>Small evaluation budget: </strong>CMA-ES is particularly useful when the evaluation budget is moderate to large (&gt; 100 x the number of hyperparameters) [6]. On the other hand, I cannot recommend you to use CMA-ES in a small evaluation budget.</li><li><strong>Distributed optimization:</strong> The concurrency model of Optuna is an <strong>asynchronous</strong> parallelization. In this model, <em>CmaEsSampler</em> cannot use some trials for updating the parameters of multivariate normal distribution. However, it is able to overcome this problem by <a href="https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.Study.html#optuna.study.Study.ask">ask-and-tell interface</a> although you need to be familiar with the design of Optuna and <em>CmaEsSampler</em>.</li><li><strong>Dynamic search space</strong>: <em>CmaEsSampler</em> does not support dynamic search space (e.g. <a href="https://github.com/optuna/optuna/blob/v2.5.0/examples/sklearn_simple.py">examples/sklearn_simple.py</a>). Therefore the parameters are sampled by <em>independent_sampler</em> (default: Random search).</li></ul><h3>Conclusion &amp; Future Work</h3><p>In this article, I introduced CMA-ES, the variants, how to use <em>CmaEsSampler</em> in Optuna, and when you should NOT use <em>CmaEsSampler</em>. As a future work, I’m planning to support the following algorithms.</p><ul><li>WS-sep-CMA-ES [3], which applies a warm starting method for sep-CMA-ES.</li><li>DTS-CMA-ES [7], which uses Gaussian Process as a surrogate model.</li><li>BIPOP-CMA-ES [2], which applies two interlaced restart strategies, one with an increasing population size and one with varying small population sizes.</li></ul><p>Finally, the entire code of <em>CmaEsSampler</em> can be found <a href="https://github.com/optuna/optuna/blob/v2.5.0/optuna/samplers/_cmaes.py">here</a>. I hope you will dive into and open pull requests for more improvements.</p><h3>References</h3><ul><li>[1] N. Hansen. The CMA Evolution Strategy: A Tutorial, arXiv:1604.00772, 2016.</li><li>[2] I. Loshchilov, M. Schoenauer, and M. Sebag. Bi-population CMA-ES Algorithms with Surrogate Models and Line Searches, GECCO Workshop, 2013.</li><li>[3] M. Nomura, S. Watanabe, Y. Akimoto, Y. Ozaki, M. Onishi. Warm Starting CMA-ES for Hyperparameter Optimization, AAAI, 2021.</li><li>[4] A. Auger, N. Hansen. A restart CMA evolution strategy with increasing population size, CEC, 2005.</li><li>[5] R. Ros, N. Hansen. A Simple Modification in CMA-ES Achieving Linear Time and Space Complexity, PPSN, 2008.</li><li>[6] F. Hutter, H. Hoos, and K. Leyton-Brown, An evaluation of sequential model-based optimization for expensive blackbox functions, GECCO Workshop, 2013.</li><li>[7] L. Bajer, Z. Pitra, J. Repicky, and M. Holeňa. Gaussian process surrogate models for the CMA evolution strategy. Evolutionary computation, 2019.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee68194c8f88" width="1" height="1" alt=""><hr><p><a href="https://medium.com/optuna/introduction-to-cma-es-sampler-ee68194c8f88">Introduction to CMA-ES sampler.</a> was originally published in <a href="https://medium.com/optuna">Optuna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The internal of go-prompt: How to control the rich terminal UI (Part I).]]></title>
            <link>https://c-bata.medium.com/the-internal-of-go-prompt-how-to-control-the-rich-terminal-ui-part-i-7d22bdfe6b9a?source=rss-a9250c4c9905------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d22bdfe6b9a</guid>
            <category><![CDATA[terminal]]></category>
            <dc:creator><![CDATA[c-bata]]></dc:creator>
            <pubDate>Sun, 25 Aug 2019 19:48:37 GMT</pubDate>
            <atom:updated>2020-07-17T02:36:46.423Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, I’m a creator of <a href="https://github.com/c-bata/go-prompt">go-prompt</a>. Fortunately, go-prompt reaches 2300 stars on Github. And many awesome OSS adopts this library today. Thank you for all the users and contributors. By using go-prompt, you can write powerful interactive prompts, like kube-prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*b5_Como_I4CBVp6kOqUm0Q.png" /><figcaption><a href="https://github.com/c-bata/kube-prompt">https://github.com/c-bata/kube-prompt</a></figcaption></figure><p>As the number of Github stars of the terminal UI projects implies, The rich terminal UI applications are very attractive for most software developers. On the other hand, I guess most software developers don’t know how does it work because you don’t need to learn about terminal control for your job.</p><p>In this article, I describe how to develop a rich Terminal UI application in Go (the reason why I use Go is its portability). Don’t worry even if you are not Gopher. You can easily apply it to your preferred language. This article is a part I of the series which consists of 3 articles.</p><ul><li><strong><em>Part I</em></strong> A brief history of terminals. What is VT-100 escape sequences? How do we get the window size of terminal emulators?</li><li><strong><em>Part II</em></strong> What is raw-mode. How to emulate the buffer information of the Terminal. (still not published)</li><li><strong><em>Part III</em></strong> Re-thinking the design of components of go-prompt for v1.0.0. (still not published)</li></ul><h3>A brief history of the terminal.</h3><p>Before digging into the source code of terminal control, let’s learn about the history of the terminal. I introduce two terminal machines here. Both of these were widely used in the past which I wasn’t still born.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*q2PRzqgTKFUS6iV6-nhyHQ.jpeg" /><figcaption>Image refers from <a href="https://en.wikipedia.org/wiki/Teletype_Model_33">wikipedia.org</a></figcaption></figure><p>In the 1960s-1970s, <strong><em>ASR-33</em></strong> produced by Teletype Corp was widely used (because of its low price and ASCII-compatibility). Then it became that these kinds of machines are called <strong><em>teletype(tty) terminal</em></strong>.</p><p>As you can see, this device embeds typewriter. Although this device could not express rich visual effects, it requires operations for breaking lines. But this is a <strong><em>dumb terminal</em></strong> which is just an output device that accepts text from <a href="https://en.wikipedia.org/wiki/Minicomputer">minicomputers</a>. So minicomputers need to send following operations to control this device.</p><ul><li>Carriage Return(CR): Reset the printhead to the beginning of a line.</li><li>Line Feed (LF): Turned the wheel to move the paper to change the line.</li></ul><p>You know, these are the root of CRLF breaking line characters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*alFl_9yMf1BqWNrl_6P2BA.jpeg" /><figcaption>Image refers from <a href="https://en.wikipedia.org/wiki/VT100">wikipedia.org</a></figcaption></figure><p>In the late 1970s, <strong><em>VT100</em></strong> is produced by DEC. This machine has a monochrome display. We couldn’t still change the color, but it enables to express the rich visual effects like blinking, erasing texts and make the texts to bold or italic.</p><p>A lot of control sequences are defined for specific operations. These are called <strong><em>VT100 escape sequences</em></strong>. As the name implies, all control sequences start from \x1b<em> </em>which corresponds<em> Escape </em>on the ASCII code table. Most of the terminal emulators on UNIX OS adopt it to control its visual effects today¹.</p><h3>VT100 escape sequences</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*B7mfr4eeu4RroIZ5rGAfoA.png" /><figcaption>Change the terminal color</figcaption></figure><p>In this section, let’s learn about VT100 escape sequences. First I describe a simple example that changes the color of texts and background. The source code is below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba3f67f6553de4aca3982a4f69572aac/href">https://medium.com/media/ba3f67f6553de4aca3982a4f69572aac/href</a></iframe><p>The source code is quite simple. Please focus on line 6, it’s a VT100 escape sequence to change the color. \x1b[4;30;46m consists of 3 parts.</p><ul><li>\x1b[ : control sequence introducer</li><li>4;30;46 : parameters which separated by a semi-colon. 4 means underline, 30 means set foreground color Black and 46 means set background color Cyan.</li><li>m : a final character (which is always one character).</li></ul><p>After printing Hello World, the code prints\x1b[0m which contains 0 which is a parameter to clear display attributes. By the way, VT100 couldn’t express the color because it embeds a monochrome display. I don’t know the details why there are control sequences for changing colors, but VT241 terminal which is the high-end model embeds color graphics display. So I guess the sequences to change the colors are added from this model. See the <a href="https://vt100.net/dec/vt_history">VT families</a> for more details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*5F8iEQ_EMK9YQEf61RQToA.gif" /></figure><p>Next, let’s write code that displays progress bar. It needs to erase the terminal and move cursor positions. So it’s a little bit complicated than the previous example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f4cb88c90582f9fb3bcd0ed2dd44a20/href">https://medium.com/media/9f4cb88c90582f9fb3bcd0ed2dd44a20/href</a></iframe><p>If you want to know more escape sequences, I recommended you to check <a href="http://www.termsys.demon.co.uk/vtansi.htm">this page</a> or <a href="http://ascii-table.com/ansi-escape-sequences-vt-100.php">this page</a>.</p><h3>How to get a window size of the Terminal emulator.</h3><p>We can change the window sizes because we use terminal emulators, not terminal machines. In this section, let’s learn about how to get the size of terminal emulators. To get the window size, you need to call ioctl(2) with TIOCGWINSZ like following².</p><pre><strong>type </strong>winsize <strong>struct </strong>{<br>   Row uint16<br>   Col uint16<br>   X  uint16<br>   Y uint16<br>}<br><br><strong>func </strong>getWinSize(fd int) (row, col uint16, err error) {<br>   <strong>var </strong>ws *winsize<br>   retCode, _, errno := syscall.Syscall(<br>      syscall.<em>SYS_IOCTL</em>, uintptr(fd),<br>      uintptr(syscall.<em>TIOCGWINSZ</em>),<br>      uintptr(unsafe.Pointer(ws)))<br>   <strong>if </strong>int(retCode) == -1 {<br>      <strong>panic(errno)</strong><br>   }<br>   <strong>return </strong>ws.Row, ws.Col, nil<br>}</pre><p>But the viewpoint of portability, it’s better to call <a href="https://godoc.org/golang.org/x/sys/unix#IoctlGetWinsize">unix.IoctlGetWinsize</a> .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd22b4e8cf986fce78eadef6a17f991f/href">https://medium.com/media/dd22b4e8cf986fce78eadef6a17f991f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*DMHm-tkLgOAtvJKkxrTrfg.gif" /><figcaption>Spread the progress bar with the window column size.</figcaption></figure><p>Not only learn about how to get the window size but also you need to know how to receive the events which notify the window size change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*KPlEvQwX6EAw0rJcwe1Wmw.gif" /><figcaption>This program has a problem that it doesn’t follow the changes of window size.</figcaption></figure><p>You can receive notification from UNIX OS signal. You just handle SIGWINCH os signals like following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5511be6226c7c149bc2ec3f3a627e6a/href">https://medium.com/media/e5511be6226c7c149bc2ec3f3a627e6a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*QarWLh1BiIErltRR52T5vg.gif" /><figcaption>Follow the changes of window size</figcaption></figure><p>By calling ioctl(2) with TIOCGWINSZ when you receive SIGWINCH , you can get the window size. You can control the terminal UI from this informations.</p><p>However, it is difficult to erase the screen properly. In fact, the output will collapse if you make the terminal window smaller in this code. The most simple method is erasing the entire screen every time. Please try it if you want to learn more.</p><h3>What you’ll learn next?</h3><p>If you understand this article, you can develop rich terminal UI applications. In the next article, I describe how to handle user inputs. If you learn the next article, you can get all the basics to develop go-prompt.</p><h3>Footnotes</h3><p>[1]: Some of the terminals for Windows don’t adopt VT100 escape sequences. I don’t know the details but it seems needs to learn about Win32 Console API.</p><p>[2]: <a href="https://twitter.com/Linda_pp">@Linda_pp</a> tells me that it’s also able to use \x1b[999C\x1b[999B\x1b[6n which moves cursor position on the bottom of right and report the cursor position (<a href="https://twitter.com/Linda_pp/status/1165900117418729473">tweet link</a>). <a href="https://twitter.com/ttdoda/">@ttdoda</a> developer of TeraTerm tweets that it might be over 1000 columns today. So resize command which is installed with xterm now uses 9999 to move the cursor (<a href="https://twitter.com/ttdoda/status/1166119504545402881">tweet link</a>). And <a href="https://twitter.com/Dubhead/status/1166025736303415302">@Dubhead</a> tells me that we can also use <a href="https://terminalguide.netlify.com/seq/csi_st-18/">\x1b[18t</a> or <a href="https://terminalguide.netlify.com/seq/csi_st-19/">\x1b[19t</a> (<a href="https://twitter.com/Dubhead/status/1166025736303415302">tweet link</a>). Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d22bdfe6b9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>