サイトのデザインが新しくなりました。

【Stable Code Instruct 3B】プログラミング言語を完全網羅したコーディングAI

Stable-Code-Instruct-3B プログラミング言語 完全網羅 コーディングAI

WEELメディア事業部LLMリサーチャーの藤崎です。

2024年3月26日、「Stable Code Instruct 3B」を、Stability AIが公開しました。
「stable-code-instruct-3b」は、Stable Code 3Bをベースにした指示学習済みのコード生成言語モデルで、自然言語プロンプトによりコード生成、数学、その他のソフトウェア開発に関連するクエリなどの様々なタスクを処理することができます。

Xでの投稿のいいね数は、すでに1000を超えており、注目されていることが分かります。

この記事ではStable Code Instruct 3Bの使い方や、有効性の検証まで行います。本記事を熟読することで、Stable Code Instruct 3Bの凄さを理解し、生成AIを利用してのプログラミングが捗ることでしょう。

ぜひ、最後までご覧ください。

なお弊社では、生成AIツール開発についての無料相談を承っています。こちらからお気軽にご相談ください。

目次

Stable Code Instruct 3Bの概要

Stable Code Instruct 3Bは自然言語プロンプトでのプログラミングが可能な「Stable Code 3B」をベースに、指示学習を施したモデルとなっています。

Stable Code 3Bはプログラミングの他にコード補完、数学的推論などを行うことができる汎用のコード言語モデルなのに対し、Stable Code Instruct 3Bは追加学習によってコード生成や問題解決を行う能力に特化したコード言語モデルです。

Stable Code Instruct 3Bの主な特徴は次のとおりです。

言語サポート: Python、C++、JavaScriptなどの主要なプログラミング言語を主な対象としていますが、モデルのトレーニングデータセットは幅広い言語を網羅しています。
指示応答性: このモデルの指示学習により、複雑で微妙なリクエストを解釈して実行することができます。この機能により、Stable Code Instruct 3Bは、より適切でコンテキストを意識したコード提案を提供し、開発者の生産性を高め、アウトプットの反復と改善を可能にします。
ハードウェアアクセシビリティ: Stable Code Instruct 3Bはコンパクトなサイズと、低いハードウェア要件により、より多くのユーザーが利用できるようになりました。コード補完やFIMタスクをサポートし、微妙なプログラミングクエリを理解することで、開発者はより少ない労力で効率的かつ効果的に作業することができます。
引用:https://ja.stability.ai/blog/stable-code-instruct-3b


このモデルは3Bという小規模なスケールながら最先端の性能を誇っており、CodeLlama 7B Instruct などより大きなサイズのモデルを凌駕しています。また、ソフトウェアエンジニアリング関連のタスクでは StarChat 15B と同等の性能を発揮するなど大規模言語モデルに引けを取らないパフォーマンスとなっています。

その証拠となる、MTベンチマークとMulti-PLベンチマークの結果です。

参照:https://ja.stability.ai/blog/stable-code-instruct-3b

Multi-PLベンチマークとは、様々なプログラミング言語で書かれたコードを理解し生成する能力を測るためのテストになるのですが、いずれのプログラミング言語でもより大きなモデルであるCodeLlamaを上回っています。

大規模言語モデルになるとそれだけマシンスペックが要求されてしまうため利用シーンも限られてしまいますが、Stable Code Instruct 3Bのように小さく高性能なモデルは様々な場面で活躍すること間違いなしですね。

なお、汎用モデルであるStable Code 3Bについては、「【やってみた】StableCode、Stability AIの自動コード生成を実践解説」を合わせてご確認ください。

Stable Code Instruct 3Bのライセンス

Stable Code Instruct 3Bは一般的なオープンソースライセンスではなく、Stability AIによるライセンスが適用されます。
非商用の研究目的でのみ利用可能ですが、Stability AIメンバーシップに加入すれば商用利用することも可能です。

利用用途可否
商用利用
改変⭕(非商用利用に限る)
配布⭕(非商用目的で、契約のコピーを第三者に提供する場合)
特許使用❌(この契約では明示的に言及されていませんが、一般的に商用利用が禁止されているため、特許使用も含めた商用目的での利用は制限される可能性があります。)
私的使用⭕(非商用目的に限る)
参考:https://huggingface.co/stabilityai/stable-code-instruct-3b/blob/main/LICENSE

Stable Code Instruct 3Bの使い方

Stable Code Instruct 3Bは2つあります。

1つ目は下記にアクセスしてHugging Faceのデモを使う方法です。

https://huggingface.co/spaces/stabilityai/stable-code-instruct-3b

2つ目はソースコードを使い、ローカルやGoogleColabで実行する方法です。今回はGoogleColabで使ってみました。

Hugging Faceに記載されているコードを使えば簡単・・・と思ったのですがそのままでは動かなかったので下記のようにひと手間加えています。

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("stabilityai/stable-code-instruct-3b", trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained("stabilityai/stable-code-instruct-3b", torch_dtype=torch.bfloat16, trust_remote_code=True)
model.eval()
model = model.cuda()

messages = [
    {
        "role": "system",
        "content": "You are a helpful and polite assistant",
    },
    {
        "role": "user",
        "content": "Write a simple website in HTML. When a user clicks the button, it shows a random joke from a list of 4 jokes."
    },
]

prompt = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)

inputs = tokenizer([prompt], return_tensors="pt").to(model.device)

tokens = model.generate(
    **inputs,
    max_new_tokens=1024,
    temperature=0.5,
    top_p=0.95,
    top_k=100,
    do_sample=True,
    use_cache=True
)

output = tokenizer.batch_decode(tokens[:, inputs.input_ids.shape[-1]:], skip_special_tokens=False)[0]
print(output)

「”role”: “user”」の「”content”:」以降がプロンプトになります。

デモに書かれているサンプルプロンプトは「ボタンをクリックしたら4つのリストからランダムでジョークが表示されるウェブサイトを作って」というものです。なんじゃそりゃ・・・。

そして追加したのは最後の「print」の箇所ですね。これがないと結果が表示されませんのでご注意ください。
では生成された解答がこちらになります!

html
<!DOCTYPE html>
<html>
<head>
	<title>Random Joke Generator</title>
</head>
<body>

<h1>Random Joke Generator</h1>

<button onclick="showJoke()">Tell me a joke!</button>

<p id="joke"></p>

<script>
// List of jokes
var jokes = [
  "Why don't scientists trust atoms? Because they make up everything!",
  "Why did the scarecrow win an award? Because he was outstanding in his field!",
  "Why did the chicken cross the playground? To get to the other slide!",
  "Why did the coffee file a police report? He got mugged!"
];

// Function to show a random joke
function showJoke() {
  // Generate a random index
  var index = Math.floor(Math.random() * jokes.length);

  // Get the joke at the random index
  var joke = jokes[index];

  // Display the joke
  document.getElementById("joke").innerHTML = joke;
}
</script>

</body>
</html>
```

This code creates a simple webpage with a button that, when clicked, displays a random joke from a list of 4 jokes. 
The jokes are stored in an array called `jokes`, and the `showJoke` function generates a random index into the array and displays the joke at that index.
The `showJoke` function is called when the button is clicked, as specified in the `onclick` attribute. The joke is displayed in a paragraph element with the id `joke`.

なんと、HTMLのコードだけでなくジョークをランダムで表示されるようにjavascriptも書かれているんです。
上記コードを表示させてみると下記の通りになりました。

「New Joke」と書かれているボタンを押せば上の文章が変わります。すごい・・・。

Stable Code Instruct 3Bを動かすのに必要なPCのスペック

Google Colab(無料プラン)
■GPU:T4
※CPUだとエラーが出てしまうので必ずGPUを選択してください

なお、大規模なコード生成モデルについて知りたい方は「【CodeLlama-70B】700億パラメーターコード生成AIをGPT-4と比較してみた」を合わせてご確認ください。

Stable Code Instruct 3Bは本当に自然言語でプログラムを作ってくれるのか試してみた

デモを実行してみただけで、Stable Code Instruct 3Bの凄さを実感していただけたと思います。ここからは更に様々なプログラムをStable Code Instruct 3Bに作ってもらいましょう!

Stable Code Instruct 3Bにコーポレートサイトを作ってもらう

まずは、冒頭のXにも掲載されていたコーポレートサイトの作成です。プロンプトは下記になります。

Create a website for my new company
Stabillity AI we are activating humanity's potential through generative AI

The color scheme should be modern and clearn

Stabillity AIのホームページを作って欲しいという内容ですね。事業内容やカラースキームなども記載されていますが果たして・・・?
生成された回答は下記の通りです。

Creating a website for a company like Stabillity AI involves coding and requires a basic understanding of HTML, CSS, and JavaScript. 
Here's a simple example of how you could structure your website:


<!DOCTYPE html>
<html>
<head>
    <title>Stabillity AI</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
    <header>
        <h1>Stabillity AI</h1>
        <p>Activing humanity's potential through generative AI</p>
    </header>
    <nav>
        <ul>
            <li><a href="#about">About</a></li>
            <li><a href="#team">Team</a></li>
            <li><a href="#contact">Contact</a></li>
        </ul>
    </nav>
    <section id="about">
        <h2>About Us</h2>
        <p>Stabillity AI is a cutting-edge artificial intelligence company focused on using technology to bring about positive change in the world. We believe that by harnessing the power of generative AI, we can help to activate humanity's potential and make a positive impact on our planet.</p>
    </section>
    <section id="team">
        <h2>Meet the Team</h2>
        <!-- Add team members here -->
    </section>
    <section id="contact">
        <h2>Contact Us</h2>
        <!-- Add contact form here -->
    </section>
    <footer>
        <p>© 2022 Stabillity AI. All rights reserved.</p>
    </footer>
</body>
</html>
This is a basic layout for your website. You'll want to replace the placeholder text and links with your own content.

To style your website, you can create a new CSS file (e.g., styles.css) and link it to your HTML file:


body {
    font-family: Arial, sans-serif;
    color: #333;
    background-color: #f4f4f4;
}

header {
    background-color: #333;
    color: #fff;
    padding: 20px;
    text-align: center;
}

nav ul {
    list-style-type: none;
    padding: 0;
    display: flex;
    justify-content: space-around;
}

section {
    padding: 20px;
}

footer {
    background-color: #333;
    color: #fff;
    text-align: center;
    padding: 10px;
    position: fixed;
    bottom: 0;
    width: 100%;
}
This is a simple example and you can add more complex features like a responsive navigation menu, a team page with member profiles, and a contact form.
Please note that you will need to have a server set up to host your website, and you'll need to learn some basic web development skills to create and style your website. 
If you're not comfortable with coding, you might want to consider using a website builder or a content management system. 
There are many options available that will allow you to create a professional-looking website without needing to code.
As for the color scheme, you can change the colors in the CSS file to match the modern and clean look you desire. 
The colors used in this example are a dark grey (#333) for text and background, a light grey (#f4f4f4) for the navigation bar, and a dark grey (#333) for the footer. You can adjust these colors to match your desired look and feel.<|im_end|>

HTMLとCSSが出力されましたね。コードの下にはサイトを実装する際の注意点やカラーコードについて書かれています。
上記のコードを実際に表示してみると下記のとおりになりました。

若干装飾が少ない気がしますが、ヘッダー・フッター・グローバルメニューがあり、レスポンシブデザインになっているのでホームページのテンプレートとしては十分使えるものではないかと思います。更に詳しくプロンプトを入力すればもっと凝ったものができそうな気がしますね。

Stable Code Instruct 3Bは日本語対応しているのか試してみた

では、日本語対応はどうなっているのか、先程のプロンプトをChatGPTに訳してもらったものをStable Code Instruct 3Bに入力してみましょう。

新しい会社「Stability AI」のウェブサイトを作成してください。
私たちは、生成AIを通じて人類の可能性を活性化しています。

色の組み合わせは、現代的でクリアなものにしてください。

回答はこちら!

Creating a website for Stability AI, a company that utilizes AI to enhance human potential, involves several steps. Here's a basic outline of how you might approach this task:
Design and Plan: Start by sketching out the layout of your website and determining the key sections you want to include. Consider using modern and clear color schemes to make your website visually appealing.
Choose a Platform: Decide where your website will be hosted. Popular options include WordPress, Squarespace, Wix, and Shopify. You could also create a static website using HTML and CSS.
Write Content: Develop content for your website. This could include information about Stability AI, its mission, values, and products/services. Ensure that your content is engaging, informative, and user-friendly.
Optimize for SEO: Search engine optimization (SEO) is crucial for driving organic traffic to your website. Ensure that your content is optimized for relevant keywords and includes meta tags for better visibility.
Include Social Media: Include social media sharing buttons and links to encourage users to share your content on social media platforms.
Create Navigation: Design a clear and intuitive navigation menu to help users easily navigate through your website.
Ensure Accessibility: Ensure that your website is accessible to all users, including those with disabilities. Use alt tags for images, provide transcripts for videos, and use semantic HTML to make your website more accessible.
Testing: Test your website on multiple devices and screen sizes to ensure a consistent user experience.
Finalize and Deploy: Once you're satisfied with your website's design, content, and functionality, finalize it and deploy it to your chosen hosting platform.
Maintain and Enhance: Regularly update your website with fresh content, fix any bugs or issues, and ensure that it remains user-friendly and effective over time.

Here's a simple example of HTML and CSS code for a basic website layout:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Stability AI</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f0f0f0;
    }

    header {
      background-color: #333;
      color: #fff;
      padding: 1rem;
    }

    nav {
      background-color: #555;
      color: #fff;
      padding: 0.5rem;
    }

    nav a {
      color: #fff;
      text-decoration: none;
      padding: 0.5rem;
    }

    main {
      padding: 2rem;
    }

    footer {
      background-color: #333;
      color: #fff;
      padding: 1rem;
      text-align: center;
    }
  </style>
</head>
<body>
  <header>
    <h1>Stability AI</h1>
  </header>
  <nav>
    <a href="#">Home</a>
    <a href="#">About</a>
    <a href="#">Products</a>
    <a href="#">Contact</a>
  </nav>
  <main>
    <h2>Welcome to Stability AI</h2>
    <p>This is an example website showcasing Stability AI's mission and products.</p>
  </main>
  <footer>
    <p>© 2022 Stability AI. All rights reserved.</p>
  </footer>
</body>
</html>
This is a very basic example, and you can expand upon it to create a more complex and visually appealing website. Remember to thoroughly test your website and make it user-friendly for all users. Good luck with your website creation!<|im_end|>

生成されたのは英語でしたが、きちんと日本語のプロンプトは認識しているようです。サイト構築の手順を細かく説明してくれています。
上記のコードの実行結果は次のようになりました。

メインコンテンツの情報量が少ない分、縦が短く見えていますがサイトの基本的なコンテンツは揃っっていますね。
今回はグローバルメニューの背景色もついていました。

何度か生成してみたのですが、カラースキームは違うもののサイト構成自体はほぼ同じものが毎回出力されました。

とはいえ、3Bという小規模モデルながらしっかりと日本語を理解しこちらの意図したコードを出力してくれるStable Code Instruct 3Bはかなり優秀なコード生成モデルと言えるでしょう。

Stable Code Instruct 3BでPythonを使ってみる

今まではStable Code Instruct 3BにHTML・CSS・Javascriptなど、ウェブ周りの開発を任せていましたが、次はPythonのプログラミング能力をチェックしてみましょう!電卓アプリのような基本的なプログラムではなく、少し難しいものをお願いしてみました。

プロンプトは下記の通りです。

There is a sales management table (sample.xlsx) that contains dates and sales figures from January 1, 2024, to January 31, 2024. 
Please create a Python program to forecast sales for February 2024 based on this sales management table.

■和訳
2024年1月1日から2024年1月31日までの日付・売上数が入力された売上管理表(sample.xlsx)がある。
この売上管理表をもとに2024年2月の売上予測を行うpythonのプログラムを作ってください。

日付と売上数が入力された簡単な売上管理表を読み込んで、次月の売上予測を行うプログラムをpythonで作ってもらいましょう!

Stable Code Instruct 3Bの答えはこちら!

To create a Python program to forecast sales for February 2024 based on the sales management table, you can use time series forecasting techniques such as ARIMA (AutoRegressive Integrated Moving Average). 
However, since we don't have the actual data, I will provide you with a general example using Python and the `pandas` and `statsmodels` libraries. You can modify the code according to your specific table structure and data.

First, make sure you have the required libraries installed:

```bash
pip install pandas statsmodels
```

Next, create a Python script with the following content:

```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.arima.model import ARIMA

# Load the sales management table (sample.xlsx)
data = pd.read_excel('sample.xlsx', index_col='Date', parse_dates=True)

# Prepare the data for forecasting
data = data.resample('D').interpolate()  # Interpolate missing values
train_data = data.loc[:'2024-01-31']
test_data = data.loc['2024-02-01':]

# Fit the ARIMA model on the training data
model = ARIMA(train_data, order=(1, 1, 1))
model_fit = model.fit()

# Forecast sales for February 2024
forecast = model_fit.forecast(steps=len(test_data))[0]

# Create a new DataFrame with the forecasted sales
forecast_df = pd.DataFrame({'Date': pd.date_range(start='2024-02-01', periods=len(forecast), freq='D'),
                            'Sales': forecast})

# Combine the original and forecasted data
full_data = pd.concat([data.loc[:'2024-02-01'], forecast_df])
full_data.plot()
plt.title('Sales Forecast for February 2024')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.show()

# Print the forecasted sales
print(forecast_df)
```

This script will load the sales management table, fit an ARIMA model on the training data, forecast sales for February 2024, and print the forecasted sales.
Keep in mind that this is just a simple example and might not provide accurate predictions. You can improve the model by considering additional factors, such as trend and seasonality, and by adjusting the order of the ARIMA model.
Also, note that the provided script assumes the sales management table has a column named 'Sales' and a column named 'Date'. If your table has different column names, update the script accordingly.

ARIMAモデルを使用すること、pandasやstatsmodelsといった必要になるライブラリ、実際のコード、注意点など非常に丁寧にプログラム案を提示してくれました。

パッと見たところ完璧に見えますが、実行すると下記のようにMA(移動平均)のパラメータでのワーニングや「forecast = ….. 」の箇所でエラーが発生していました。各エラーを修正すれば売上予測のレポートが出力されましたが、生成されたコードをそのまま利用するのは注意が必要ですね。

■エラーコード

/usr/local/lib/python3.10/dist-packages/statsmodels/tsa/statespace/sarimax.py:978: UserWarning:
 Non-invertible starting MA parameters found. Using zeros as starting parameters.
  warn('Non-invertible starting MA parameters found.'
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-21-7b41552ab93f> in <cell line: 19>()
     17 
     18 # Forecast sales for February 2024
---> 19 forecast = model_fit.forecast(steps=len(test_data))[0]
     20 
     21 # Create a new DataFrame with the forecasted sales

5 frames
/usr/local/lib/python3.10/dist-packages/statsmodels/tsa/base/tsa_model.py in get_prediction_index(start, end, nobs, base_index, index, silent, index_none, index_generated, data)
    387     # Validate prediction options
    388     if end < start:
--> 389         raise ValueError("Prediction must have `end` after `start`.")
    390 
    391     # Handle custom prediction index

ValueError: Prediction must have `end` after `start`.

今回はざっくりしたプロンプトだったので、もう少し詳しく条件などを指定すれば正常に動作するプログラムを作ってくれるかもしれませんね。

なお、高度なプログラミングコード生成する他のLLMについては「【AlphaCodium】Googleを超える最強コード生成AIが競プロで優勝できるか試してみた」を合わせご確認ください。

Stable Code Instruct 3Bを使えば爆速でプログラミングを終えることができる!

本記事では、Stable Code Instruct 3Bについてご紹介しました。

3Bという比較的小規模なモデルでありながら、大規模なコード開発モデルと同等以上の性能を持つStable Code Instruct 3Bは非常に使い勝手のいいものとなっています。

実際、無料のGoogleColab上でも動作したので必要スペックはかなり低いため、誰でも使うことができるでしょう。

今回の検証の中で、HTML・CSS・Javascriptなどを利用してホームページを作るという課題に対しては、かなり精度の高いコードを生成してくれました。

一方、Pythonでエクセルからの売上予測を行うプログラムは途中でエラーが出てしまうという結果に。こちらはプロンプトの内容が甘い部分もあったかなと思うのですが、エラーが出たとはいえ必要なライブラリやプログラムの注意点なども細かく示してくれていました。

LLMは入力するプロンプトによって精度に違いが出てくるので、Stable Code Instruct 3Bにあったプロンプトを見つけることができればプログラムの実装や修正などにかかる作業時間が大幅に削減できるはずです。

最後に

いかがだったでしょうか?

弊社では

・マーケティングやエンジニアリングなどの専門知識を学習させたAI社員の開発
・要件定義・業務フロー作成を80%自動化できる自律型AIエージェントの開発
・生成AIとRPAを組み合わせた業務自動化ツールの開発
・社内人事業務を99%自動化できるAIツールの開発
ハルシネーション対策AIツールの開発
自社専用のAIチャットボットの開発

などの開発実績がございます。

まずは、「無料相談」にてご相談を承っておりますので、ご興味がある方はぜひご連絡ください。

➡︎生成AIを使った業務効率化、生成AIツールの開発について相談をしてみる。

生成AIを社内で活用していきたい方へ

「生成AIを社内で活用したい」「生成AIの事業をやっていきたい」という方に向けて、生成AI社内セミナー・勉強会をさせていただいております。

セミナー内容や料金については、ご相談ください。

また、弊社紹介資料もご用意しておりますので、併せてご確認ください。

投稿者

  • 藤崎

    情シスとして8年間勤務したあと、現在はWEBコンサルタントとして独立。 システム開発やマーケティング、ライター、プログラミング教室など幅広い分野で活動中。 と言えば聞こえはいいですが、実際のところはITの何でも屋さんみたいなことをしています。

  • URLをコピーしました!
  • URLをコピーしました!
目次