<?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 Cerebrium on Medium]]></title>
        <description><![CDATA[Stories by Cerebrium on Medium]]></description>
        <link>https://medium.com/@cerebriumai?source=rss-3e2acdad466b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dKRv5TFojqLEYJoRBRmMKw.jpeg</url>
            <title>Stories by Cerebrium on Medium</title>
            <link>https://medium.com/@cerebriumai?source=rss-3e2acdad466b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 00:19:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cerebriumai/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[Getting better price-performance, latency, and availability on AWS Trn1/Inf2 instances]]></title>
            <link>https://cerebriumai.medium.com/getting-better-price-performance-latency-and-availability-on-aws-trn1-inf2-instances-c0eabbb443ee?source=rss-3e2acdad466b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0eabbb443ee</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[tensorrt]]></category>
            <dc:creator><![CDATA[Cerebrium]]></dc:creator>
            <pubDate>Fri, 17 May 2024 01:10:23 GMT</pubDate>
            <atom:updated>2024-05-17T01:10:23.260Z</atom:updated>
            <content:encoded><![CDATA[<p>At Cerebrium, the feedback we get from customers daily is that they want their applications to run faster and cheaper. While we have been described as wizards by some, there are many avenues we have seen customers achieve this with some possible options being:</p><ul><li>To use specialized frameworks such as vLLM or Tensor-TRT to improve inference speed and/or throughput.</li><li>To use batching that allows customers to increase GPU utilization.</li><li>Semantic caching in order to avoid making a LLM call. We will do a future tutorial on this.</li><li>Using MIG instances to fractionalize GPU’s. We will do a future tutorial on this.</li><li>Lastly, to use more specialized or powerful hardware.</li></ul><p>At Cerebrium, we want to offer engineers the flexibility to build the applications they envision using the tools they require — essentially we want to meet engineers where they work. This entails us offering the flexibility to build applications the way in which they want but also to run on the hardware that best suits their use case. With that being said, Cerebrium now officially supports AWS Tranium and Inferentia 2 — based Amazon Trn1 and inf2 instances.</p><p>Both Amazon EC2 Trn1 and Inf2 instances offer a great performance/price trade-off that makes it suitable for many companies running inference at scale. We have seen latency and throughput be similar if not better than traditional Nvidia chips such as A10, L4 and A100. Additionally, it is a great alternative to avoid capacity shortages against A100/H100’s where stability is top of mind for enterprise use cases.</p><p>In this tutorial, we will show you how you can deploy the Llama 3 8B model using Inf2 and/or Trn1 instances on Cerebrium. We will compare both throughput, latency and cost as those in our <a href="https://www.cerebrium.ai/blog/running-llama-3-8b-with-tensorrt-llm-on-serverless-gpus">previous blog</a> post running TensorRT-LLM on Nvidia instances. By the end of this tutorial you deploy a auto-scaling Llama 3 endpoint on AWS Inf2 where you only pay for the compute you use.</p><p>You can view the final code <a href="https://github.com/CerebriumAI/examples/tree/master/14-inferentia">here</a></p><h3>Inferentia &amp; Trainium Overview</h3><p>AWS Inferentia 2 are specialized machine learning chips designed to optimize deep learning inference workloads, offering a cost-effective and efficient alternative for applications requiring high-throughput and low-latency processing. AWS Inferentia2 accelerator delivers up to 4x higher throughput and up to 10x lower latency compared to the original Inferentia chips. For many ML use cases, we have seen Inferentia 2 be up to 50% cheaper than similar AI chips while giving the same performance.</p><p>AWS Trainium is a specialized machine learning chip designed by AWS to optimize deep learning training workloads, offering a cost-effective and efficient alternative for applications requiring high-throughput and low-latency processing.</p><p>Amazon Neuron SDK is used to run deep learning workloads on AWS Inferentia and AWS Trainium based instances. It includes a deep learning compiler, runtime, and tools that are natively integrated into TensorFlow, PyTorch and Apache MXNet.</p><h3>Setup</h3><p>If you don’t have a Cerebrium account, you can create one by signing up<a href="https://dashboard.cerebrium.ai/register"> here</a> and following the documentation<a href="https://docs.cerebrium.ai/cerebrium/getting-started/installation"> here</a> to get setup</p><p>In your IDE, run the following command to create our Cerebrium starter project: cerebrium init inferentia. This creates two files:</p><ul><li><a href="http://main.py/">Main.py</a> — Our entrypoint file where our code lives</li><li>cerebrium.toml — A configuration file that contains all our build and environment settings</li></ul><h3>Deploying on Inferentia 2</h3><p>You can see many examples and tutorials from the Neuron documentation<a href="https://awsdocs-neuron.readthedocs-hosted.com/en/latest/general/models/index.html"> here</a>.</p><p>To deploy to Inf2 nodes through Cerebrium, you can change the “gpu” type to “INF2” under the [cerebrium.hardware] heading in your cerebrium.toml file. We will automatically use a base image that has the various Neuron drivers installed.</p><p>In this tutorial, we will be using <a href="https://docs.vllm.ai/en/latest/getting_started/installation.html">vLLM</a>, which is an easy to use framework that optimizes inferencing and serving of models. Recently, vLLM added support for Neuron and so we will do it to increase the performance of our models. You can follow the instructions<a href="https://docs.vllm.ai/en/latest/getting_started/neuron-installation.html"> here</a> on how to get started with vLLM on Neuron. Since our base image contains the necessary libraries you can skip to step 2. We show the steps below:</p><p>You can add the following shell commands to your cerebrium.toml under [cerebrium.build]:</p><pre>shell_commands = [<br>&quot;pip install torch==2.1.* --index-url &quot;,<br>&quot;pip install wget&quot;,<br>&quot;pip install awscli&quot;,<br>&quot;pip install neuronx-cc==2.* torch-neuronx==2.1.* torchvision transformers-neuronx --extra-index-url=https://pip.repos.neuron.amazonaws.com&quot;,<br>&quot;pip install ray huggingface_hub pydantic triton&quot;,<br>&quot;git clone &quot;,<br>&quot;cd vllm &amp;&amp; git checkout 6ef09b08f88b675f84b7140238286e5d4c5304c8 &amp;&amp; pip install -U -r requirements-neuron.txt --extra-index-url=https://pip.repos.neuron.amazonaws.com &amp;&amp; pip install . --extra-index-url=https://pip.repos.neuron.amazonaws.com &amp;&amp; cd ..&quot;,<br>]</pre><p>This code is installing the various python packages as well as building vLLM from source. You will notice we checkout a specific hash in the above code, that is because at the time of writing the latest version has a problem on Neuron.</p><p>To start we need to go to HuggingFace and accept the model permissions for<a href="https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct"> Lllama 3 8B</a> if we haven’t already. It takes about 30 minutes or less for them to accept your request. Since HuggingFace requires you to be authenticated to download the model weights, we need to authenticate ourselves in Cerebrium before downloading the model.</p><p>In your Cerebrium dashboard you can add your HuggingFace token as a secret by navigating to “Secrets” in the sidebar. For the sake of this tutorial I called mine “HF_AUTH_TOKEN”. We can now access these values in our code at runtime without exposing them in our code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*idJ2RikMb6J1qSWn.png" /></figure><p>Cerebrium Secrets Dashboard</p><p>We can then add the following code to our<a href="http://main.py/"> main.py</a> in order to run llama3 using vLLM.</p><pre>from vllm import LLM, SamplingParams<br>import huggingface_hub<br>import time<br>import torch<br>from transformers import AutoTokenizer<br>from huggingface_hub import login<br>from cerebrium import get_secret<br><br>class Item(BaseModel):<br>    prompts: list[str] = []<br>    temperature: Optional[float] = 0.8<br>    top_p: Optional[float] = 0.95<br>    <br>login(token = get_secret(&quot;HF_AUTH_TOKEN&quot;)<br><br>model_id = &quot;meta-llama/Meta-Llama-3-7B-Instruct&quot;<br>llm = LLM(<br>    model=model_id,<br>    max_num_seqs=1,<br>    max_model_len=128,<br>    block_size=128,<br>    # The device can be automatically detected when AWS Neuron SDK is installed.<br>    # The device argument can be either unspecified for automated detection,<br>    # or explicitly assigned.<br>    device=&quot;neuron&quot;,<br>    tensor_parallel_size=8)<br>tokenizer = AutoTokenizer.from_pretrained(model_id)<br><br>def predict(<br>        prompts,<br>        temperature = 0.8,<br>        top_p = 0.95<br>    ):<br>    item = Item(prompts=prompts, temperature=temperature, top_p=top_p)<br><br>    # Start timing<br>    start_time = time.time()<br><br>    sampling_params = SamplingParams(temperature=item.temperature, top_p=item.top_p)<br>    outputs = llm.generate(item.prompts, sampling_params)<br>  <br>  total_tokens = 0<br>  generated_texts = []  # List to store all generated texts<br>  for output in outputs:<br>      prompt = output.prompt<br>      generated_text = output.outputs[0].text<br>      print(f&quot;Prompt: {prompt!r}, Generated text: {generated_text!r}&quot;)<br>      generated_texts.append(generated_text)<br>  <br>      # Assuming you have a way to count tokens, e.g., a function count_tokens(text)<br>      total_tokens += len(tokenizer.tokenize(prompt)) + len(tokenizer.tokenize(generated_text))<br><br># Calculate duration and tokens per second<br>duration = end_time - start_time<br>tokens_per_second = total_tokens / duration if duration &gt; 0 else 0<br><br>print(f&quot;Processed {total_tokens} tokens in {duration:.2f} seconds ({tokens_per_second:.2f} tokens/second)&quot;)</pre><p>To break down the code above:</p><ul><li>First set up our Pydantic object which makes sure that our incoming requests take on a specific format. Some parameters are optional so we set default values for that.</li><li>Use our Hugging Face secret in order login to authenticate the Llama 3 download.</li><li>Next create your LLM object. Neuron has some very specific settings here:some text</li></ul><ol><li><strong>max_num_seqs</strong>: Denotes the maximum number of sequences or inputs that can be processed simultaneously by the model during inference. Here, it’s set to 16, meaning the model can handle up to 16 input sequences at once. The higher the batch, the more GPU memory required.</li><li><strong>max_model_len</strong>: Represents the maximum length of input sequences or tokens that the model can process. In this case, it’s set to 128, indicating that the maximum length of the input text or tokens should not exceed 128.</li><li><strong>block_size</strong>: Refers to the block size used for processing input data. This needs to be the same as the max_model_len.</li><li><strong>device</strong>: Specifies the target device for model execution. In this scenario, it’s set to “neuron”, indicating that the model is intended to run on AWS Neuron instances.</li><li><strong>tensor_parallel_size</strong>: This parameter is related to parallel processing of tensors. It’s set to 2, suggesting that the model may be optimized for parallel execution across two tensor processing units or cores. You can set the number of “GPU’s” in your cerebrium.toml file. Just note that 1 “GPU” in your cerebrium.toml is associated with 2 neuron cores.</li></ol><p>Lastly, we pass our input prompts to our model and time how long it takes to execute.</p><h3>Deploy on Cerebrium</h3><p>In order to deploy your code to Cerebrium, run cerebrium deploy. The first build will take roughly 20 minutes since all the dependencies will be installed and the model has to be compiled based on the settings you set above. Subsequent changes will be much faster since dependencies and the model will be cached. If you change any model settings like the batch size or the tensor_parallel_size, the model will need to be recompiled.</p><p>The model needs to be compiled with 6 CPUs and 60GB of memory, which you set in your cerebrium.toml — it requires a lot of power! Once it’s working, we recommend redeploying with 2 CPUs and 14 GB memory in order to get the same performance for a much lower cost.</p><p>Once completed, it should output a curl which you can copy and paste to test your inference endpoint.</p><pre><br>curl --location &#39;&#39; \\<br>--header &#39;Content-Type: application/json&#39; \\<br>--header &#39;Authorization: Bearer XXXXX&#39; \\<br>--data &#39;{&quot;prompt&quot;: &quot;Hello World!&quot;}&#39;</pre><p>We get the following results on Inf2 nodes with different settings:</p><h4>Throughput</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LKZa4WkgreME9_eE.png" /></figure><h4>Latency</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J_IYU34zf5l1HWre.png" /></figure><p>‍If you compare this to the performance from our previous article, an Ampere A10 had a throughput of ~600 tokens per second (FP16) at a cost of $0.000555 per second. Inferentia are able to generate 435 tokens at a cost of $0.000479 per second.Therefore TensorRT on an A10 provides slightly better price/performance tradeoff. However, Inferentia generates a per token latency of 32.25ms per token whereas TensorRT was 41.77ms per second and therefore is better for latency sensitive applications.</p><p>Comparatively, you can run a Llama 3 70b model at 223 tokens per second at a cost of $0.00271 per second vs using TensorRT which has a throughput of 663 across 2 80GB GPUs at a cost of $0.00358 per second. Therefore you are getting ~⅓ of the throughput for 25% less cost. One big consideration to take into account is that you do not face the availability issues that face A100’s.</p><h3>Conclusion</h3><p>In conclusion, the deployment of the Llama 3 model on Inf2 instances offers a significant improvement in throughput and latency, at a potentially lower cost compared to traditional methods. Additional, as advancements are released with the vLLM framework you will be able to take advantage of this. This tutorial demonstrates how Cerebrium’s flexibility allows engineers to run applications on hardware that best suits their use case, and presents a step-by-step process for deploying on inf2 nodes. The results show that both setups offer efficient processing capabilities, with specific advantages in different contexts. As technology continues to evolve, we can expect further improvements and increased efficiency in deep learning inference workloads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SARoKOGmypZcCh5aGVzeVA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0eabbb443ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Llama 3 8B with TensorRT-LLM on Serverless GPUs]]></title>
            <link>https://cerebriumai.medium.com/running-llama-3-8b-with-tensorrt-llm-on-serverless-gpus-046d1f9a4b7c?source=rss-3e2acdad466b------2</link>
            <guid isPermaLink="false">https://medium.com/p/046d1f9a4b7c</guid>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[tensorrt-llm]]></category>
            <category><![CDATA[meta-llama-3]]></category>
            <dc:creator><![CDATA[Cerebrium]]></dc:creator>
            <pubDate>Wed, 01 May 2024 02:33:14 GMT</pubDate>
            <atom:updated>2024-05-01T02:33:14.690Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial blog post, we will guide you through the process of implementing the TensorRT-LLM framework to serve Llama 3 8B model on the Cerebrium platform. TensorRT-LLM is a powerful framework that can be used to optimise machine learning models for inference. It can lead to significant improvements in performance, especially in terms of inference speed and throughput.</p><p>In this tutorial we will achieve ~1700 output tokens per second on a single Nvidia A10 instance however you can go up to ~4500 output tokens per second on a single Nvidia A100 40GB instance or even ~19,000 tokens on a H100. For further improvements, you can use speculative sampling or FP8 quantisation to increase latency and throughput. You can view the official benchmarks across different GPU types, model sizes and input/output token lengths <a href="https://github.com/NVIDIA/TensorRT-LLM/blob/71d8d4d3dc655671f32535d6d2b60cab87f36e87/docs/source/performance.md">here</a>.</p><h3>Overview</h3><p>TensorRT-LLM is a specialised library within NVIDIA’s TensorRT, a high-performance deep learning inference platform. It is designed to accelerate large language models (LLMs) using NVIDIA GPUs. It can significantly improve the performance of your machine learning models however it comes at the expense of a very complicated setup process.</p><p>You are required to convert and build the model using very specific arguments that replicate your workloads as closely as possible. If you don’t configure these steps properly, you might witness subpar performance and subsequently it will become very complicated to deploy. We will cover these concepts in depth throughout the tutorial.</p><h3>Cerebrium Setup</h3><p>If you don’t have a Cerebrium account, you can create one by signing up <a href="https://dashboard.cerebrium.ai/register">here</a> and following the documentation <a href="https://docs.cerebrium.ai/cerebrium/getting-started/installation">here</a> to get setup</p><p>In your IDE, run the following command to create our Cerebrium starter project: cerebrium init llama-3b-tensorrt. This creates two files:</p><ul><li><a href="http://main.py/">Main.py</a> — Our entrypoint file where our code lives</li><li>cerebrium.toml — A configuration file that contains all our build and environment settings‍</li></ul><p>TensorRT-LLM has a demo implementation of Llama on its Github repo which you can look at <a href="https://github.com/NVIDIA/TensorRT-LLM/tree/main/examples/llama">here</a>. The first thing you will notice is that TensorRT-LLM requires Python 3.10. Subsequently, the code that converts the model weights to the TensorRT format requires a lot of memory and so we need to set this in our configuration file. Please change your <strong>cerebrium.toml file</strong> to reflect the below:</p><pre>[cerebrium.deployment]<br>name = &quot;llama-3b-tensorrt&quot;<br>python_version = &quot;3.10&quot;<br>include = &quot;[./*, main.py, cerebrium.toml]&quot;<br>exclude = &quot;[./example_exclude]&quot;<br>cuda_version = &quot;12&quot;<br><br>[cerebrium.hardware]<br>region = &quot;us-east-1&quot;<br>provider = &quot;aws&quot;<br>gpu = &quot;AMPERE_A10&quot;<br>cpu = 3<br>memory = 40.0<br>gpu_count = 1</pre><p>The most important decision to make is to decide what GPU chip you would like to run on. Larger models, longer sequence lengths and bigger batches all require more GPU memory and so if throughput is your desired metric, we recommend using a A100/H100. In this example we went with a A10 which gives a good cost/performance trade-off. Also, there is no capacity shortages and so its more stable for low-latency enterprise workloads. However, if this is a requirement for you — please reach out.</p><p>Let us then install the required <em>pip</em> and <em>apt</em> requirements. You can add the following to your <strong>cerebrium.toml</strong></p><pre>[cerebrium.dependencies.pip]<br>transformers = &quot;latest&quot;<br>torch = &quot;&gt;=2.0.0&quot;<br>pydantic = &quot;latest&quot;<br>huggingface-hub = &quot;latest&quot;<br>flax = &quot;latest&quot;<br>h5py = &quot;latest&quot;<br>sentencepiece = &quot;latest&quot;<br>easydict = &quot;latest&quot;<br>mpmath = &quot;==1.3.0&quot;<br><br>[cerebrium.dependencies.apt]<br>software-properties-common = &quot;latest&quot;<br>gcc = &quot;latest&quot;<br>&quot;g++&quot; = &quot;latest&quot;<br>aria2 = &quot;latest&quot;<br>git = &quot;latest&quot;<br>git-lfs = &quot;latest&quot;<br>wget = &quot;latest&quot;<br>openmpi-bin = &quot;latest&quot;<br>libopenmpi-dev = &quot;latest&quot;</pre><p>We want to install the tensorrt_llm package after the above installs and want to grab it from the Nvidia PyPI index url. To do this, we use shell commands which allows you to run command line arguments during the build process — this happens as the last step of the build process (ie: post pip, apt and conda installs).</p><p>Add the following under [cerebrium.build] in your <strong>cerebrium.toml:</strong></p><pre>shell_commands = [ &quot;pip install tensorrt_llm -U --pre --extra-index-url https://pypi.nvidia.com https://pypi.nvidia.com/&quot;]</pre><p>We then need to write an initial code in our <a href="http://main.py/">main.py</a> that will:</p><ul><li>Download Llama 3 7B from HuggingFace</li><li>Convert the model checkpoints</li><li>Build the TensorTRT-LLM inference engine.‍</li></ul><p>At the moment, Cerebrium does not have a way to run code only during the build process (work in progress) however, one easy way for us to side step this is to check if the file output from the <em>trtllm-build</em> step already exists meaning its been converted.</p><p>To start we need to go to HuggingFace and accept the model permissions for <a href="https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct">Lllama 7B</a> if we haven’t already. It takes about 30 minutes or less for them to accept your request. Since HuggingFace requires you to be authenticated to download the model weights, we need to authenticate ourselves in Cerebrium before downloading the model.</p><p>In your Cerebrium dashboard you can add your HuggingFace token as a secret by navigating to “Secrets” in the sidebar. For the sake of this tutorial I called mine “HF_AUTH_TOKEN”. We can now access these values in our code at runtime without exposing them in our code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rPOQXo6qMOMNm3KC.png" /></figure><p>You can then add the following code to your <a href="http://main.py/">main.py</a> to download the model:</p><pre>from huggingface_hub import snapshot_download<br>from cerebrium import get_secret<br><br>huggingface_hub.login(token=get_secret(&quot;HF_AUTH_TOKEN&quot;))<br><br>MODEL_ID=&quot;meta-llama/Meta-Llama-3-8B-Instruct&quot;<br>MODEL_DIR=&quot;/persistent-storage/model_input&quot;<br>ENGINE_DIR=&quot;/persistent-storage/model_output&quot;<br><br>if not os.path.exists(ENGINE_DIR):<br>	snapshot_download(<br>	      MODEL_ID,<br>	      local_dir=MODEL_DIR,<br>	      ignore_patterns=[&quot;*.pt&quot;, &quot;*.bin&quot;],  # using safetensors<br>	  )In the above code, we login to HuggingFace using our HF_AUTH_TOKEN and download the Llama 3 7B model. We check if the ENGINE_DIR exists as a way to prevent running this code on cold start but rather only running this if it the final TensorRT-LLM engine files don’t exist.</pre><h3>Setup TensorRT-LLM</h3><p>Next, we need to convert the downloaded model. We can use the script that exists in the <a href="https://github.com/NVIDIA/TensorRT-LLM/tree/main/examples/llama">tensorRT-LLM</a> repo. To download this script to your Cerebrium instance put the following code in your shell commands.</p><pre>[&quot;wget https://raw.githubusercontent.com/NVIDIA/TensorRT-LLM/71d8d4d3dc655671f32535d6d2b60cab87f36e87/examples/llama/convert_checkpoint.py -O ./convert_checkpoint.py&quot;]</pre><p>This downloads the specific script file to your instance. Shell commands works as an array of strings so you can just add it to the existing shell command already there.</p><h3>Converting and Compiling TensorRT-LLM engine</h3><p>Below we convert the model into float16 format, the reason being that it results in marginally higher performance over float32. You can go even further and use the quantised model (FP8) which will give you the lowest latency.</p><p>What allows TensorRT-LLM to achieve its high throughput is that it is compiled in advance to predefined settings which you set based on your expected workloads. This therefore makes concrete choices of the CUDA kernels to execute for each operation which are then optimized for specific types and shapes of tensors for the specific hardware it runs on.</p><p>So we need to specify the maximum input and output lengths as well as the typical batch size. The closer these values are to production, the higher our throughput will be. There are many different options you can pass to the command <em>trtllm-build</em> to tune the engine for your specific workload, we selected just two plugins that accelerate two core components. You can read more about the plugin options <a href="https://fetch.ai/blog/advancing-llm-optimization">here</a>.</p><p>We then need to run the convert_checkpoint script and then run the <em>trtllm-build</em> script in order to build the TensorTRT-LLM model. You can add the following code to your <a href="http://main.py/">main.py</a>:</p><pre>import tensorrt_llm<br>import subprocess<br>import torch<br><br>MAX_INPUT_LEN, MAX_OUTPUT_LEN = 256, 256<br>MAX_BATCH_SIZE = (<br>    128 <br>)<br><br>if not os.path.exists(ENGINE_DIR):<br> #snapshot_download(<br>	      MODEL_ID,<br> 				...<br>  )<br>  <br> # Build the TRT engine<br>        convert_checkpoint = f&quot;&quot;&quot;<br>	python convert_checkpoint.py --model_dir {MODEL_DIR} \\<br>	                            --output_dir ./model_ckpt \\<br>	                            --dtype float16<br>	&quot;&quot;&quot;<br>	<br>	SIZE_ARGS = f&quot;--max_batch_size={MAX_BATCH_SIZE} --max_input_len={MAX_INPUT_LEN} --max_output_len={MAX_OUTPUT_LEN}&quot;<br>	build_engine = f&quot;&quot;&quot;<br>	trtllm-build --checkpoint_dir ./model_ckpt --output_dir {ENGINE_DIR} \\<br>	          --tp_size=1 --workers=1 \\<br>	          --max_batch_size={MAX_BATCH_SIZE} --max_input_len={MAX_INPUT_LEN} --max_output_len={MAX_OUTPUT_LEN} \\<br>	          --gemm_plugin=float16 --gpt_attention_plugin=float16<br>	&quot;&quot;&quot;<br>	<br>	print(&quot;Building engine...&quot;)<br>	subprocess.run(convert_checkpoint, shell=True, check=True)<br>	subprocess.run(build_engine, shell=True, check=True)<br>	print(&quot;\\nEngine built successfully! You can find it at: &quot;, ENGINE_DIR)<br>else:<br>    print(&quot;Engine already exists at: &quot;, ENGINE_DIR)</pre><p>You will see we run these command line arguments as a subprocess. The reason I did it like this and not as shell commands is:</p><ul><li>Currently Cerebrium doesn’t support Secrets in shell commands and I need the model to be downloaded before I can continue with the other model conversion steps.</li><li>It seems much cleaner to reuse variables and use subprocesses than squash everything in the <strong>cerebrium.toml</strong> file.‍</li></ul><h3>Model Instantiation</h3><p>Now that our model is converted with our specifications, let us initialise the model and set it up based on our requirements. This code will run on every cold start and takes roughly ~10–15s to load the model into GPU memory. If the container is warm, it will run your predict function immediately which we talk about in the next section.</p><p>Above your predict function, add the following code.</p><pre>from tensorrt_llm.runtime import ModelRunner<br>from transformers import AutoTokenizer<br><br>tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)<br># LLaMA models do not have a padding token, so we use the EOS token<br>tokenizer.add_special_tokens(<br>    {&quot;pad_token&quot;: tokenizer.eos_token}<br>)<br># and then we add it from the left, to minimize impact on the output<br>tokenizer.padding_side = &quot;left&quot;<br>pad_id = tokenizer.pad_token_id<br>end_id = tokenizer.eos_token_id<br><br>runner_kwargs = dict(<br>    engine_dir=f&quot;{ENGINE_DIR}&quot;,<br>    lora_dir=None,<br>    rank=tensorrt_llm.mpi_rank(),<br>)<br><br>model = ModelRunner.from_dir(**runner_kwargs)</pre><p>We need to pass the input that a user sends into our prompt template and cater for special tokens. Add the the following function that will handle this for us</p><pre>def parse_input(<br>        tokenizer,<br>        input_text,<br>        prompt_template=None,<br>        add_special_tokens=True,<br>        max_input_length=923<br>    ):<br><br># Apply prompt template if provided<br>    if prompt_template is not None:<br>        input_text = prompt_template.format(input_text=input_text)<br><br># Encode the text to input IDs<br>    input_ids = tokenizer.encode(<br>        input_text,<br>        add_special_tokens=add_special_tokens,<br>        truncation=True,<br>        max_length=max_input_length,<br>    )<br><br> # Convert to tensor<br>    input_ids_tensor = torch.tensor([input_ids], dtype=torch.int32)  # Add batch dimension<br><br>return input_ids_tensor</pre><p>Before we get to our predict function that runs at runtime we need to define our Pyandtic object that will make sure user requests conform to this standard as well as have default values.</p><pre>from typing import Optional<br>from pydantic import BaseModel<br><br>class Item(BaseModel):<br>    prompt: str<br>    temperature: Optional[float] = 0.95<br>    top_k: Optional[int] = 100<br>    top_p: Optional[float] = 1.0<br>    repetition_penalty: Optional[float] = 1.05<br>    num_tokens: Optional[int] = 250<br>    prompt_template: Optional[str] = &quot;user\\n{input_text}\\nmodel\\n&quot;</pre><h3>Inference function</h3><p>Lastly, let us bring this all together with our predict function</p><pre>def predict(item, run_id, logger):<br>    item = Item(**item)<br>    <br>    stop_words_list = None<br>    bad_words_list = None<br><br>    batch_input_ids = parse_input(<br>        tokenizer=tokenizer,<br>        input_text=item.prompt,<br>        prompt_template=item.prompt_template<br>    )<br>    input_length = batch_input_ids[0].size(0)<br>    time_begin = time.time()<br>    <br>    with torch.no_grad():<br>        outputs = model.generate(<br>            batch_input_ids,<br>            max_new_tokens=item.num_tokens,<br>            max_attention_window_size=None,<br>            sink_token_length=None,<br>            end_id=end_id,<br>            pad_id=pad_id,<br>            temperature=item.temperature,<br>            top_k=item.top_k,<br>            top_p=item.top_p,<br>            num_beams=1,<br>            repetition_penalty=item.repetition_penalty,<br>            stop_words_list=stop_words_list,<br>            bad_words_list=bad_words_list,<br>            output_sequence_lengths=True,<br>            return_dict=True,<br>        )<br>        torch.cuda.synchronize()<br><br>    time_total = time.time() - time_begin<br><br>    output_ids = outputs[&quot;output_ids&quot;]<br>    sequence_lengths = outputs[&quot;sequence_lengths&quot;]<br><br>    # Decode the output<br>    output_begin = input_length<br>    output_end = sequence_lengths<br>    output_text = tokenizer.decode(output_ids[0][0][output_begin:output_end].tolist())<br><br>    return {<br>        &quot;response_txt&quot;: output_text,<br>        &quot;latency_s&quot;: time_total,<br>    }</pre><p>Now that our code is deployed, we can deploy the application with the command: cerebrium deploy<em>.</em></p><p>On initial deploy, it will take about 15–20 minutes since besides installing all your packages and dependancies, it will download the model and convert it to the TensorRT-LLM format. Once completed, it should output a curl which you can copy and paste to test your inference endpoint.</p><pre>curl --location &#39;&#39; \\<br>--header &#39;Content-Type: application/json&#39; \\<br>--header &#39;Authorization: XXXXX&#39; \\<br>--data &#39;{&quot;prompt&quot;: &quot;Tell me about yourself?&quot;}&#39;</pre><p>TensorRT-LLM is one of the top performing inference frameworks on the market and especially if you know details about your expected future workloads. You should now have a low latency endpoint with high throughput that can auto-scale to tens of thousands of inferences all while only paying for the compute you use.</p><p>To view the final version of the code, you can look <a href="https://github.com/CerebriumAI/examples/tree/master/15-tensor-trt">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1UQ46Sa2_ylbwDhpprS6gA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=046d1f9a4b7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an Executive Assistant using LangChain, LangSmith, Cerebrium and Cal.com]]></title>
            <link>https://cerebriumai.medium.com/creating-an-executive-assistant-using-langchain-langsmith-cerebrium-and-cal-com-5da2a66888bd?source=rss-3e2acdad466b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5da2a66888bd</guid>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[langchain-agents]]></category>
            <category><![CDATA[cerebrium]]></category>
            <dc:creator><![CDATA[Cerebrium]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 14:17:55 GMT</pubDate>
            <atom:updated>2024-04-18T14:17:55.457Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>As a startup founder, I have a very specific way that I like to split my time since I usually need to be everywhere all at once. What has worked best for me is:</p><ul><li>Mornings are for my team <strong>only,</strong> in order to sync on current priorities as well as make sure no one is blocked. It’s also the time when I like to do my most demanding work.</li><li>Afternoons are for customers or potential partnership meetings since I am usually not at my mental peak (I am always at my peak).</li><li>Nights are for me to catch up on planning, as well as meeting with any friends or other entrepreneurs who ask me for help, advice etc.‍</li></ul><p>I have never thought about getting an executive assistant since I don’t think its worth the cost at this stage but it would be nice to not organise my calendar everyday. Also its a flex when someone says “Claire will coordinate a time for us to connect” because it suggests that their time is valuable.</p><p>I have been meaning to try out <a href="https://www.langchain.com/langsmith">LangSmith</a>, the monitoring tool from <a href="https://www.langchain.com/">LangChain</a> and I thought an agent to manage my calendar would be a fun project. I also feel like with all the advancements in text-to-speech (TTS) models, I could make this pretty professional given enough time. I’m hoping the open-source world can take this example and run with it!</p><p>In this tutorial, I am going to create an executive assistant, Cal-vin, to manage my calendar (<a href="http://cal.com/">Cal.com</a>) with employees, customers, partners and friends. I will use the LangChain SDK to create my agent, the LangSmith platform to monitor how it is scheduling my time throughout the day and monitor situations in which it fails to do a correct job. Lastly, we will deploy this application on Cerebrium to show how it handles deploying and scaling our application seamlessly.</p><p>You can find the final version of the code <a href="https://github.com/CerebriumAI/examples/tree/master/13-tool-calling-langsmith">here</a>.</p><h3>Concepts</h3><p>To create an application like this, we will need to interact with my calendar based on instructions from a user. This is a perfect use case for an agent with function (tool) calling ability. LangChain is a framework with a lot of functionality supporting agents, they are also the creators of LangSmith and so an integration should be relatively easy.</p><p>When we refer to a tool, we are referring to any framework, utility, or system that has defined functionality around a use case. For example, we might have a tool to search Google, a tool to pull our credit card transactions etc.</p><p>LangChain also has three concepts/functions that we need to understand:</p><ul><li>ChatModel.bind_tools(): This is a method for attaching tool definitions to model calls. Each model provider has a different way they expect tools to be defined however; LangChain has created a standard interface so you can switch between providers and it is versatile. You can pass in a tool definition (a dict), as well as other objects from which a tool definition can be derived: namely Pydantic classes, LangChain tools, and arbitrary functions etc. The tool definition tells the LLM what this tool does and how to interact with it.AIMessage.tool_calls: This is an attribute on the AIMessage type returned from the model for easily accessing the tool calls the model decided to make. It will specify any tool invocations in the format specified from the bind_tools call:</li></ul><pre><br>@tool<br>def exponentiate(x: float, y: float) -&gt; float:<br>    &quot;&quot;&quot;Raise &#39;x&#39; to the &#39;y&#39;.&quot;&quot;&quot;<br>    return x**y</pre><ul><li>AIMessage.tool_calls: This is an attribute on the AIMessage type returned from the model for easily accessing the tool calls the model decided to make. It will specify any tool invocations in the format specified from the bind_tools call:</li></ul><pre># -&gt; AIMessage(<br>#    content=...,<br>#    additional_kwargs={...},<br>#    tool_calls=[{&#39;name&#39;: &#39;exponentiate&#39;, &#39;args&#39;: {&#39;y&#39;: 2.743, &#39;x&#39;: 5.0}, &#39;id&#39;: &#39;54c166b2-f81a-481a-9289-eea68fc84e4f&#39;}]<br>#    response_metadata={...},<br>#    id=&#39;...&#39;<br>#   )</pre><ul><li>create_tool_calling_agent(): The tool_calling_agent is just a standard way to bring the above concepts all together to work across providers that have different formats so you can easily switch out models.</li></ul><pre>agent = create_tool_calling_agent(llm, tools, prompt)<br>agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)<br><br>agent_executor.invoke({&quot;input&quot;: &quot;what&#39;s 3 plus 5 raised to the 2.743. also what&#39;s 17.24 - 918.1241&quot;, })</pre><h3>Setup <a href="http://calc.com/">Calc.com</a></h3><p>I am a big fan of <a href="http://cal.com/">Cal.com</a> and believe the team is going to keep shipping incredible features and so wanted to build a demo using them. If you do not have an account you can create one <a href="https://app.cal.com/signup">here</a>. Cal will be our source of truth, so if you update time zones, or working hours in Cal, our assistant will reflect that.</p><p>Once your account is created, click on “API keys” in the left sidebar and create an API key with no expiration date.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PvbRHCKPs3AwrrnV.png" /><figcaption>Cal.com API keys</figcaption></figure><p>To test that it’s working, you can do a simple CURL request. Just replace the following variables below:</p><ul><li>Username</li><li>API key</li><li>Update the dateFrom and to dateTo variables</li></ul><pre>curl --location &#39;https://api.cal.com/v1/availability?apiKey=cal_live_xxxxxxxxxxxxxx&amp;dateFrom=2024-04-15T00%3A00%3A00.000Z&amp;dateTo=2024-04-22T00%3A00%3A00.000Z&amp;username=michael-louis-xxxx&#39;</pre><p>You should get a response similar to the following:</p><pre>{<br>    &quot;busy&quot;: [<br>        {<br>            &quot;start&quot;: &quot;2024-04-15T13:00:00.000Z&quot;,<br>            &quot;end&quot;: &quot;2024-04-15T13:30:00.000Z&quot;<br>        },<br>        {<br>            &quot;start&quot;: &quot;2024-04-22T13:00:00.000Z&quot;,<br>            &quot;end&quot;: &quot;2024-04-22T13:30:00.000Z&quot;<br>        },<br>        {<br>            &quot;start&quot;: &quot;2024-04-29T13:00:00.000Z&quot;,<br>            &quot;end&quot;: &quot;2024-04-29T13:30:00.000Z&quot;<br>        },<br>    ....<br>    ],<br>    &quot;timeZone&quot;: &quot;America/New_York&quot;,<br>    &quot;dateRanges&quot;: [<br>        {<br>            &quot;start&quot;: &quot;2024-04-15T13:45:00.000Z&quot;,<br>            &quot;end&quot;: &quot;2024-04-15T16:00:00.000Z&quot;<br>        },<br>        {<br>            &quot;start&quot;: &quot;2024-04-15T16:45:00.000Z&quot;,<br>            &quot;end&quot;: &quot;2024-04-15T19:45:00.000Z&quot;<br>        },<br>     ....<br>        {<br>            &quot;start&quot;: &quot;2024-04-19T18:45:00.000Z&quot;,<br>            &quot;end&quot;: &quot;2024-04-19T21:00:00.000Z&quot;<br>        }<br>    ],<br>    &quot;oooExcludedDateRanges&quot;: [<br>        <br>    ],<br>    &quot;workingHours&quot;: [<br>        {<br>            &quot;days&quot;: [<br>                1,<br>                2,<br>                3,<br>                4,<br>                5<br>            ],<br>            &quot;startTime&quot;: 780,<br>            &quot;endTime&quot;: 1260,<br>            &quot;userId&quot;: xxxx<br>        }<br>    ],<br>    &quot;dateOverrides&quot;: [],<br>    &quot;currentSeats&quot;: null,<br>    &quot;datesOutOfOffice&quot;: {}<br>}</pre><p>Great! Now we know that our API key is working and pulling information from our calendar. The API calls we will be using later in this tutorial are:</p><ul><li>/availability: Get your availability</li><li>/bookings: Book a slot‍</li></ul><h3>Cerebrium setup</h3><p>If you don’t have a Cerebrium account, you can create one by signing up <a href="https://dashboard.cerebrium.ai/register">here</a> and following the documentation <a href="https://docs.cerebrium.ai/cerebrium/getting-started/installation">here</a> to get setup</p><p>In your IDE, run the following command to create our Cerebrium starter project: cerebrium init agent-tool-calling. This creates two files:</p><ul><li><a href="http://main.py/">Main.py</a> — Our entrypoint file where our code lives</li><li>cerebrium.toml — A configuration file that contains all our build and environment settings‍</li></ul><p>Add the following pip packages near the bottom of your cerebrium.toml. This will be used in creating our deployment environment.</p><pre>[cerebrium.dependencies.pip]<br>pydantic = &quot;latest&quot;<br>langchain = &quot;latest&quot;<br>pytz = &quot;latest&quot; ##this is used for timezones<br>openai = &quot;latest&quot;<br>langchain_openai = &quot;latest&quot;</pre><p>We will be using OpenAI GPT3.5 for our use cases and so we need an API key from them. If you don’t have an account, you can <a href="https://openai.com/">sign up</a> here. You can then create an API key <a href="https://platform.openai.com/settings/profile?tab=api-keys">here</a>. The API key should be in the format: “sk_xxxxx”.</p><p>In your Cerebrium dashboard you can then add your <a href="http://cal.com/">Cal.com</a> and OpenAI API keys as secrets by navigating to “Secrets” in the sidebar. For the sake of this tutorial I called mine “CAL_API_KEY” and “OPENAI_API_KEY”. We can now access these values in our code at runtime without exposing them in our code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hI0eBcoG-wjIIpuh.png" /><figcaption>Cerebrium Secrets Dashboard</figcaption></figure><h3>Agent Setup</h3><p>To start we need to write two tool functions that the agent will use to check availability on our calendar as well as book a slot.</p><ul><li>Get availability tool</li><li>You would have seen from the test API request we did above to <a href="http://cal.com/">Cal.com</a> that the API returns your availability in the following way:</li><li>The time slots that you are already busy</li><li>Your working hours on each day‍</li></ul><p>Below is the code to achieve this</p><pre>from langchain_core.tools import tool<br>from cerebrium import get_secret<br>import requests<br>from cal import find_available_slots<br><br>@tool<br>def get_availability(fromDate: str, toDate: str) -&gt; float:<br>    &quot;&quot;&quot;Get my calendar availability using the &#39;fromDate&#39; and &#39;toDate&#39; variables in the date format &#39;%Y-%m-%dT%H:%M:%S.%fZ&#39;&quot;&quot;&quot;<br><br>    url = &quot;https://api.cal.com/v1/availability&quot;<br>    params = {<br>        &quot;apiKey&quot;: get_secret(&quot;CAL_API_KEY&quot;),<br>        &quot;username&quot;: &quot;xxxxx&quot;,<br>        &quot;dateFrom&quot;: fromDate,<br>        &quot;dateTo&quot;: toDate<br>    }<br>    response = requests.get(url, params=params)<br>    if response.status_code == 200:<br>        availability_data = response.json()<br>        available_slots = find_available_slots(availability_data, fromDate, toDate)<br>        return available_slots<br>    else:<br>        return {}</pre><p>In the above snippet we are doing a few things:</p><ul><li>We give our function the @tool decorator so that LangChain can tell the LLM this is a tool.</li><li>We write a docstring that explains to the LLM what this function does and what input it expects.The LLM will make sure it asks the user enough questions in order to collect this input data.</li><li>We wrote a helper function, find_available_slots, in order to take the information returned from the <a href="http://cal.com/">Cal.com</a> API and format it so its more readable. It will show the user the time slots available on each day.</li></ul><p>‍We then follow a similar practice to write our book_slot tool. This will book a slot in my calendar based on the selected time/day.</p><pre>@tool<br>def book_slot(datetime: str, name: str, email: str, title: str, description: str) -&gt; float:<br>    &quot;&quot;&quot;Book a meeting on my calendar at the requested date and time using the &#39;datetime&#39; variable. Get a description about what the meeting is about and make a title for it&quot;&quot;&quot;<br>    url = &quot;https://api.cal.com/v1/bookings&quot;<br>    params = {<br>        &quot;apiKey&quot;: get_secret(&quot;CAL_API_KEY&quot;),<br>        &quot;username&quot;: &quot;xxxx&quot;,<br>        &quot;eventTypeId&quot;: &quot;xxx&quot;,<br>        &quot;start&quot;: datetime,<br>        &quot;responses&quot;: {<br>            &quot;name&quot;: name,<br>            &quot;email&quot;: email,<br>            &quot;metadata&quot;: {},<br>            &quot;location&quot;: &quot;Cerebrium HQ&quot;<br>        },<br>        &quot;timeZone&quot;: &quot;America/New York&quot;,<br>        &quot;language&quot;: &quot;en&quot;,<br>        &quot;title&quot;: title,<br>        &quot;description&quot;: description,<br>    }<br>    response = requests.post(url, params=params)<br>    if response.status_code == 200:<br>        booking_data = response.json()<br>        return booking_data<br>    else:<br>        print(&#39;error&#39;)<br>        print(response)<br>        return {}</pre><p>Now that we have created our two tools let us create our agent:</p><pre>from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder<br>from langchain_core.tools import tool<br>from langchain.agents import create_tool_calling_agent, AgentExecutor<br>from langchain_openai import ChatOpenAI<br><br>prompt = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;you&#39;re a helpful assistant managing the calendar of Michael Louis. You need to book appointments for a user based on available capacity and their preference. You need to find out if the user is: From Michaels team, a customer of Cerebrium or a friend or entrepreneur. If the person is from his team, book a morning slot. If its a potential customer for Cerebrium, book an afternoon slot. If its a friend or entrepreneur needing help or advice, book a night time slot. If none of these are available, book the earliest slot. Do not book a slot without asking the user what their preferred time is. Find out from the user, their name and email address.&quot;), <br>    MessagesPlaceholder(variable_name=&quot;chat_history&quot;),<br>    (&quot;human&quot;, &quot;{input}&quot;), <br>    MessagesPlaceholder(variable_name=&quot;agent_scratchpad&quot;),<br>])<br><br>tools = [get_availability, book_slot]<br><br><br>llm = ChatOpenAI(model=&quot;gpt-3.5-turbo-0125&quot;, temperature=0, api_key=get_secret(&quot;OPENAI_API_KEY&quot;))<br>agent = create_tool_calling_agent(llm, tools, prompt)<br>agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)</pre><p>The above snippet is used to create our agent executor which consists of:</p><ul><li>Our prompt template:</li><li>This is where we can give instructions to our agent on what role it is taking on, its goal and how it should perform in certain situations etc. The more precise and concise this is, the better.</li><li>Chat History is where we will inject all previous messages so that the agent has context on what was said previously.</li><li>Input is new input from the end user.</li><li>We then instantiate our GPT3.5 model that will be the LLM we will be using. You can swap this our with Antrophic or any other provider just by replacing this one line — LangChain makes this seamless.</li><li>Lastly, we join this all together with our tools to create an agent executor.</li></ul><h3>Setup Chatbot</h3><p>The above code is static in that it will only reply to our first question but we might need to have a conversation in order to find a time that suits both the user and my schedule. We therefore need to create a chatbot with tool calling capabilities and the ability to remember past messages. LangChain supports this with RunnableWithMessageHistory().</p><p>It essentially allows us to store the previous replies of our conversation in a chat_history variable (mentioned above in our prompt template) and tie this all to a session identifier so your API can remember information pertaining to a specific user/session. Below is our code in order to implement this:</p><pre><br>from langchain.memory import ChatMessageHistory<br>from langchain_core.runnables.history import RunnableWithMessageHistory<br><br>demo_ephemeral_chat_history_for_chain = ChatMessageHistory()<br>conversational_agent_executor = RunnableWithMessageHistory(<br>    agent_executor,<br>    lambda session_id: demo_ephemeral_chat_history_for_chain,<br>    input_messages_key=&quot;input&quot;,<br>    output_messages_key=&quot;output&quot;,<br>    history_messages_key=&quot;chat_history&quot;,<br>)</pre><p>Let us run a simple local test to make sure everything is working as expected.</p><pre>class Item(BaseModel):<br>    prompt: str<br>    session_id: str<br>    <br>def predict(item, run_id, logger):<br>    item = Item(**item)<br><br>    output = conversational_agent_executor.invoke(<br>        {<br>            &quot;input&quot;: user_input,<br>        },<br>        {&quot;configurable&quot;: {&quot;session_id&quot;: item.session_id}},<br>    )<br><br>    return {&quot;result&quot;: output} # return your results<br><br>if __name__ == &quot;__main__&quot;:<br>    while True:<br>        user_input = input(&quot;Enter the input (or type &#39;exit&#39; to stop): &quot;)<br>        if user_input.lower() == &#39;exit&#39;:<br>            break<br>        result = predict({&quot;prompt&quot;: user_input, &quot;session_id&quot;: &quot;12345&quot;}, &quot;test&quot;, logger=None)<br>        print(result)</pre><p>The above code does the following:</p><ul><li>We define a Pydantic object which specifies the parameters our API expects — the user prompt and a session id to tie the conversation to.</li><li>The predict function in Cerebrium is the entry point for our API so we just pass the prompt and session id to our agent and print the results.‍</li></ul><p>To run this, simply run the following in your terminal: python <a href="http://main.py/">main.py</a>. You will need to replace your secrets with the actual values when running locally. You should then see output similar to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OE_0dzMDxXQ0dRPB.png" /><figcaption>Agent Output</figcaption></figure><p>If you keep talking and answering, you will see it will eventually book a slot.</p><h3>Integrate Langsmith</h3><p>When releasing an application to production, its vital to know how it is performing, how users are interacting with it, where is it going wrong etc. This is especially true for agent applications since they have indeterministic workflows based on how a user interacts with the application and so we want to make sure we handle any and all edge cases. LangSmith is a logging, debugging and monitoring tool from LangChain that we will use. Your can read more about LangSmith <a href="https://docs.smith.langchain.com/monitoring">here</a>.</p><p>Lets setup LangSmith in order to monitor and debug our application. First, add LangSmith as a pip dependancy to our cerebrium.toml file.</p><p>Next, we need to create an account on LangSmith and generate and API key — its free 🙂. You can sign up for an account <a href="https://smith.langchain.com/">here</a> and can generate an API key by clicking the settings (gear icon) bottom left.</p><p>Next we need to set the following environment variables. You can add the following code at the top of your main.py. You can add the API key to your secrets in Cerebrium</p><pre>import os<br>os.environ[&#39;LANGCHAIN_TRACING_V2&#39;]=&quot;true&quot;<br>os.environ[&#39;LANGCHAIN_API_KEY&#39;]=get_secret(&quot;LANGCHAIN_API_KEY&quot;)</pre><p>In order to integrate tracing into your applications it is as easy as adding the @traceable decorator to your function(s). LangSmith automatically traverses our functions and subsequent calls so we need to only put it above the predict function and we will see all the tool invocations and OpenAI responses automatically. If there is a function, that predict doesn’t call for example, but you instantiate another way, then make sure to decorate it with traceable. Edit <a href="http://main.py/">main.py</a> to have the following:</p><pre>from langsmith import traceable<br><br>@traceable<br>def predict(item, run_id, logger):</pre><p>Easy! Now LangSmith is set up. Run python <a href="http://main.py/">main.py</a> to run your file and test booking an appointment with yourself.</p><p>After you have completed a successful test run you should see data populating in LangSmith. You should see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eSrkXvMTURSYCyhR.png" /><figcaption>LangSmith Runs Dashboard</figcaption></figure><p>In the Runs tab, you can see all your runs (ie: invocations/API requests).</p><p>In 1 above, it takes the name of our function, input is set to the Cerebrium RunID which in this case we set to “test”. Lastly, you can see the input as well as the total latency of your run.</p><p>LangSmith wants you to create various automations based on your data. These can be:</p><ul><li>Sending data to annotation queues that your team needs to label for positive and negative use cases</li><li>Sending to datasets that you can eventually train a model on</li><li>Online evaluation is a new feature that allows you to use a LLM to evaluate data for rudeness, topic etc.</li><li>Triggering webhook endpoints</li><li>and much more…‍</li></ul><p>You can set these automations by clicking the “Add rule” button above (2) and specifying under what conditions you would like the above to occur. The options to create a rule on are a filter, a sampling rate, and an action.</p><p>Lastly, in 3 you can see overall metrics about your project such as number of runs, error rate, latency etc.</p><p>Since our interface is conversational, there are many use cases where you would like to follow the conversation between your agent and a user without all the bloat. Threads in LangSmith does exactly this. I can see how a conversation evolved over time and if something seems out of the ordinary, I can open the trace to dive deeper. Note that threads are associated with the session id we gave to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9PPhMTmimfh1E3Ba.png" /><figcaption>LangSmith Threads</figcaption></figure><p>Lastly, you can monitor performance metrics regarding your agent in the Monitor tab. It shows metrics such as trace count, LLM call success rate, First time for token and much more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rvk5J7VsoeDS-X-g.png" /><figcaption>LangSmith Performance Monitoring</figcaption></figure><p>LangSmith is a great choice of tool for those building agents and one that’s extremely simple to integrate. There is so much more functionality that we didn’t explore but its covers a lot of functionality in the application feedback loop of , collecting/annotating data → monitoring and then repeating</p><h3>Deploy to Cerebrium</h3><p>To deploy this application to Cerebrium you can simply run the command: <strong>cerebrium deploy</strong> in your terminal. Just make sure to delete the <strong>name</strong> == “<strong>main</strong>” code since that was just to run locally.</p><p>If it deployed successfully, you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oh59iOZkEPWPwJ-p.png" /><figcaption>Cerebrium Successful deployment</figcaption></figure><p>You can now call this via an API endpoint and our agent will remember the conversation as long as the session id is the same. Cerebrium will automatically scale up your application based on demand and only pay for the compute you use.</p><pre>{<br>    &quot;run_id&quot;: &quot;UHCJ_GkTKh451R_nKUd3bDxp8UJrcNoPWfEZ3AYiqdY85UQkZ6S1vg==&quot;,<br>    &quot;status_code&quot;: 200,<br>    &quot;result&quot;: {<br>        &quot;result&quot;: {<br>            &quot;input&quot;: &quot;Hi! I would like to book a time with Michael the 18th of April 2024.&quot;,<br>            &quot;chat_history&quot;: [],<br>            &quot;output&quot;: &quot;Michael is available on the 18th of April 2024 at the following times:\n1. 13:00 - 13:30\n2. 14:45 - 17:00\n3. 17:45 - 19:00\n\nPlease let me know your preferred time slot. Are you from Michael&#39;s team, a potential customer of Cerebrium, or a friend/entrepreneur seeking advice?&quot;<br>        }<br>    },<br>    &quot;run_time_ms&quot;: 6728.828907012939,<br>    &quot;process_time_ms&quot;: 6730.178117752075<br>}</pre><p>You can find the final version of the code <a href="https://github.com/CerebriumAI/examples/tree/master/13-tool-calling-langsmith">here</a>.</p><h3>Further improvements</h3><p>In this tutorial I didn’t get to the following but I think it would be interesting to implement:</p><ul><li>You can stream back the responses to the user to make the experience more seamless. LangChain makes it easy to do this.</li><li>Integrate with my email, that if I tag Claire in a thread, it can go through the conversation and get context to schedule the meeting.</li><li>Add voice capabilities so that someone can phone me and book a time and Claire can respond.</li></ul><h3>‍Conclusion</h3><p>The integration of LangChain, LangSmith and Cerebrium make it extremely easy to deploy agents at scale! LangChain is a great frameworks for the orchestration of LLM’s, tooling, memory as well as LangSmith for monitoring this in production and using it to identify and iterate on edge cases. Cerebrium makes this agent scalable across across 100’s or 1000’s or CPU/GPU’s while only allowing you to pay for compute as its used.</p><p>Tag us as <strong>@cerebrimai</strong> in extensions you make to the code repository so we can share it with our community.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5da2a66888bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Productionize your Comfy UI Workflow]]></title>
            <link>https://cerebriumai.medium.com/productionize-your-comfy-ui-workflow-d2594c0ae31a?source=rss-3e2acdad466b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2594c0ae31a</guid>
            <category><![CDATA[comfy-ui]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[generative-ai-solution]]></category>
            <category><![CDATA[cloud-gpu]]></category>
            <category><![CDATA[cerebrium]]></category>
            <dc:creator><![CDATA[Cerebrium]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 11:48:00 GMT</pubDate>
            <atom:updated>2024-04-18T11:48:00.627Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p><a href="https://github.com/comfyanonymous/ComfyUI">ComyUI</a> is a popular no-code interface for building complex stable diffusion workflows. Due to its ease of use, modular setup as well as its intuitive flowchart interface, the community of ComfyUI users have built a pretty phenomenal collection of workflows! There are even websites dedicated to the sharing of workflows built to help get you started:</p><ul><li><a href="https://comfyworkflows.com/">https://comfyworkflows.com/</a></li><li><a href="https://openart.ai/workflows/home">https://openart.ai/workflows/home</a>‍‍</li></ul><p>While it is currently easy to experiment with ComfyUI workflows, there isn’t a lot of guidance or tutorials on how to productionise these workflows at scale. In this tutorial, I am going to show you how you can use Cerebrium to deploy your pipelines to an API endpoint so they can autoscale based on demand and that you only pay for the compute you use.</p><p>You can find the full example code <a href="https://github.com/CerebriumAI/examples/tree/master/12-comfyui">here.</a></p><h3>Creating your Comfy UI workflow locally</h3><p>We first need to create our workflow which you can do locally on your machine or by renting a GPU from <a href="https://lambdalabs.com/">Lambda Labs</a>.</p><p>Before we get started, make sure ComfyUI is <a href="https://github.com/comfyanonymous/ComfyUI#installing">installed properly on your local environment</a>.</p><p>For our use case we are going to use Stable Diffusion XL and ControlNet to create a cool QR code. If you have a existing workflow setup, you can simply skip to the step “Export ComfyUI Workflow”</p><ol><li>Let us first create our Cerebrium project with: cerebrium init comfyUI</li><li>Inside your project, lets copy the ComfyUI GitHub project: git clone <a href="https://github.com/comfyanonymous/ComfyUI">https://github.com/comfyanonymous/ComfyUI</a></li><li>Download the following models and install them in the appropriate folders within the ComfyUI folder:</li></ol><ul><li><a href="https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_base_1.0.safetensors">SDXL base</a> in models/checkpoints.</li><li><a href="https://huggingface.co/diffusers/controlnet-canny-sdxl-1.0/resolve/main/diffusion_pytorch_model.fp16.safetensors">ControlNet</a> in models/ControlNet.</li></ul><p>4. In order to run ComfyUI locally, run the command: python main.py --force-fp16 on MacOS. Make sure you run this inside the ComfyUI folder you just cloned.</p><p>5. A server should be loaded locally at <a href="http://127.0.0.1:8188/">http://127.0.0.1:8188/</a>‍‍</p><p>In this view, you should be able to see the default user interface for a ComfyUI workflow. You can use this locally running instance to create your image generation pipeline.</p><h3>Export ComfyUI Workflow</h3><p>In our example Github repository, we have a <strong>worklow.json</strong> file. You can click the “Load” button on the right in order to load in our workflow. You then should see the workflow populated</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B8Gak4_HtrP6yr2n.png" /><figcaption>ComfyUI workflow</figcaption></figure><p>Don’t worry about the pre-filled values and prompts, we will edit these values on inference when we run our workflow.</p><p>In order to export this workflow to work with Cerebrium, we need to export this to an API format. In the top right over that hovering box on the right. Click the gear icon (settings). You must then make sure that “Enable dev mode” is <strong>selected</strong> and then can close the popup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5sjWRsTJLki4OFwI.png" /><figcaption>ComfyUI Settings</figcaption></figure><p>You should then see that a button appear on the right hover box that reads “Save (API format)”. Use that to save your workflow with the name “<strong>workflow_api.json</strong>”</p><h3>ComfyUI Application</h3><p>Our main application code lives in <strong>main.py</strong> so we now use the exported ComfyUI API workflow file above in order to create an API endpoint for our workflow. In the code below we initialize the ComfyUI server and load in our workflow API template. In our <strong>predict</strong> function, we then send in the various values we would like to alter in our workflow ie: prompt, image and run the workflow. Our function then users the inputs to alter the ComfyUI workflow values and then generates the output which in this case is base64 encoded images.</p><p>In Cerebrium, the code outside the <strong>predict</strong> function runs only on initialisation (ie: startup) where as subsequent requests will only run the predict function.</p><p>We need to alter our workflow_api.json file to have placeholders so that we can replace user values on inference. You can alter the file as follows.</p><ul><li>Replace line 4, the seed input, with: “{{seed}}”</li><li>Replace line 45, the input text of node 6 with: “{{positive_prompt}}”</li><li>Replace line 58, the input text of node 7 with: “{{negative_prompt}}”</li><li>Replace line 108, the image of node 11 with: “{{controlnet_image}}”‍</li></ul><p>We created a file that contains utility functions to make it easier to work with ComfyUI. You can find the code here. Create a file named <strong>helpers.py</strong> and copy the code into there.</p><pre>from typing import Optional<br>from pydantic import BaseModel<br><br>import copy<br>import json<br>import os<br>import time<br>import uuid<br>from multiprocessing import Process<br>from typing import Dict<br><br>import websocket<br>from helpers import (<br>    convert_outputs_to_base64,<br>    convert_request_file_url_to_path,<br>    fill_template,<br>    get_images,<br>    setup_comfyui,<br>)<br><br>server_address = &quot;127.0.0.1:8188&quot;<br>client_id = str(uuid.uuid4())<br>original_working_directory = os.getcwd()<br>global json_workflow<br>json_workflow = None<br><br>global side_process<br>side_process = None<br>if side_process is None:<br>    side_process = Process(<br>        target=setup_comfyui,<br>        kwargs=dict(<br>            original_working_directory=original_working_directory,<br>            data_dir=&quot;&quot;,<br>        ),<br>    )<br>    side_process.start()<br><br># Load the workflow file as a python dictionary<br>with open(<br>    os.path.join(&quot;./&quot;, &quot;workflow_api.json&quot;), &quot;r&quot;<br>) as json_file:<br>    json_workflow = json.load(json_file)<br><br># Connect to the ComfyUI server via websockets<br>socket_connected = False<br>while not socket_connected:<br>    try:<br>        ws = websocket.WebSocket()<br>        ws.connect(<br>            &quot;ws://{}/ws?clientId={}&quot;.format(server_address, client_id)<br>        )<br>        socket_connected = True<br>    except Exception as e:<br>        print(&quot;Could not connect to comfyUI server. Trying again...&quot;)<br>        time.sleep(5)<br><br>print(&quot;Successfully connected to the ComfyUI server!&quot;)<br><br>class Item(BaseModel):<br>    workflow_values: Optional[Dict] = None<br><br>def predict(item, run_id, logger):<br>    item = Item(**item)<br><br>    template_values = item.workflow_values<br><br>    template_values, tempfiles = convert_request_file_url_to_path(template_values)<br>    json_workflow_copy = copy.deepcopy(json_workflow)<br>    json_workflow_copy = fill_template(json_workflow_copy, template_values)<br>    outputs = {}  # Initialize outputs to an empty dictionary<br><br>    try:<br>        outputs = get_images(<br>            ws, json_workflow_copy, client_id, server_address<br>        )<br><br>    except Exception as e:<br>        print(&#39;did it get here&#39;)<br>        print(&quot;Error occurred while running Comfy workflow: &quot;, e)<br><br>    for file in tempfiles:<br>        file.close()<br><br>    result = []<br>    print(&#39;here&#39;)<br>    for node_id in outputs:<br>        for unit in outputs[node_id]:<br>            file_name = unit.get(&quot;filename&quot;)<br>            file_data = unit.get(&quot;data&quot;)<br>            output = convert_outputs_to_base64(<br>                node_id=node_id, file_name=file_name, file_data=file_data<br>            )<br>            result.append(output)<br><br>    return {&quot;result&quot;: result}</pre><h3>Deploy ComfyUI Application</h3><p>If we run cerebrium deploy it will upload the ComfyUI directory and our ~10GB of model weights so if you have a slow internet connection this can be a pain. However, in our repo we have a helper file that will download the models weights for us and put it in the appropriate folder. Create a file called model.json with the following contents:</p><pre>[<br>    {<br>        &quot;url&quot;: &quot;https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_base_1.0.safetensors&quot;,<br>        &quot;path&quot;: &quot;models/checkpoints/sd_xl_base_1.0.safetensors&quot;<br>    },<br>    {<br>        &quot;url&quot;: &quot;https://huggingface.co/diffusers/controlnet-canny-sdxl-1.0/resolve/main/diffusion_pytorch_model.fp16.safetensors&quot;,<br>        &quot;path&quot;: &quot;models/controlnet/diffusers_xl_canny_full.safetensors&quot;<br>    }<br>]</pre><p>This file is basically telling our helper function the url to download the model from and the directory to save the file in. It will only download the file on first deploy. On subsequent deploys, we wrote the logic to skip downloading the model if the file already exists.</p><p>This is what your file folder structure should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*G5uW3u0h67i3Eak8.png" /><figcaption>File Structure</figcaption></figure><p>You can now deploy your application by running: cerebrium deploy</p><p>Once your ComfyUI application has been deployed successfully, you should be able to make a request to the endpoint using the following JSON payload:</p><pre><br>curl --location &#39;https://run.cerebrium.ai/v3/p-xxxx/comfyui/predict&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--header &#39;Authorization: &#39; \<br>--data &#39;{&quot;workflow_values&quot;: {<br>  &quot;positive_prompt&quot;: &quot;A top down view of a mountain with large trees and green plants&quot;,<br>  &quot;negative_prompt&quot;: &quot;blurry, text, low quality&quot;,<br>  &quot;controlnet_image&quot;: &quot;https://cerebrium-assets.s3.eu-west-1.amazonaws.com/qr-code.png&quot;,<br>  &quot;seed&quot;: 1000<br>}<br>}&#39;</pre><p>You will get two responses from the output:</p><ul><li>The base64 encoded image of the outline of your original ControlNet image. This is what it uses as a input in your flow.</li><li>A base64 encoded image of the final result.‍</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k1Wuvp3kq-UabMMd.png" /><figcaption>Final Output QR code</figcaption></figure><h3>Conclusion</h3><p>With Cerebrium, companies can implement productionised instances of their ComfyUI workflows to create unique user experiences. Users can have peace of mine that their workloads will autoscale with demand and will only charge based on the compute used. We are excited to see what you build and please tag <strong>@cerebriumai</strong> so we can share your work</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2594c0ae31a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-tuning and deploying a Stable Diffusion model Pipeline with Cerebrium]]></title>
            <link>https://cerebriumai.medium.com/fine-tuning-and-deploying-a-stable-diffusion-model-pipeline-with-cerebrium-c59d2e3cd3c9?source=rss-3e2acdad466b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c59d2e3cd3c9</guid>
            <category><![CDATA[stable-diffusion]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[generative-art]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <dc:creator><![CDATA[Cerebrium]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 18:08:20 GMT</pubDate>
            <atom:updated>2023-07-25T18:08:20.995Z</atom:updated>
            <content:encoded><![CDATA[<p>Stable Diffusion is coming up on its one year anniversary after being released by StablilityAI and has since taken the world by storm with no signs of slowing down. A year into the release, we at Cerebrium are still seeing customers investing time and research into developing some phenomenal applications using Stable Diffusion.</p><p>Many of our customers wanted to have end-to-end pipelines as a way of implementing personalised models for their users and did not want to focus on scripts and cumbersome pipelines. They also wanted to rapidly iterate with different parameters and imagery to see what would generate the best results.</p><p>Thats why we at Cerebrium implemented an end-to-end pipeline to fine-tune Stable Diffusion v1.5 with just a few lines of code! Before we show you the workflow it’s important to walk through some best practice and some theory behind the model so you can optimise your results. In this tutorial we will be fine-tuning a model based on our CEO, Michael, since he is the “face” of Cerebrium.</p><h4>Theory</h4><p>Stable Diffusion was trained on 5 billion image-text pairs that was derived from a Common Crawl dataset scraped from the Web. Due to this diverse set of training data, we only need to supply ~10-20 images in order to get phenomenal results.</p><p>The first tip is to give a diverse set of images that showcase different facial views (like front, profile, mixed angles), expressions (such as neutral, happy, sad), and diverse backgrounds. This allows our model to produce great results with a variety of prompts rather than a small subset.</p><p>Next is to tag them with a text prompt. According to DreamBooth’s guidelines, the prompt we will use should follow the format:</p><p>A [token name] [class noun]</p><p>where the [token name] will act as our personal reference, and the [class noun] represents a pre-existing category in the model’s vocabulary that pertains to us. So for Michael, a suitable prompt could be “A CerebriumCeo man.” Other possible class nouns could include woman, child, teenager, dog, or sunglasses. Using a unique identifier and class noun during training, help the mode comprehend that we are trying to generate humans and not kitchen appliances.</p><p>However, before we refine this model, two prevalent issues need to be addressed:</p><ol><li><strong>Overfitting</strong>. Stable Diffusion would overfit such a small amount of images, regardless of how diverse they are. This means that our model will generate images in the poses and contexts that are present in the training pictures which we might not want.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VToZubTTefUQVCH5bP-1ag.jpeg" /></figure><p>2.<strong> Language drift</strong>. The model replaces a class noun with the images we gave it rather than remembering what it was trained on. For example, using “a CerebriumCeo man” is going to make the model think that all men look like Michael.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-Tnn4z6iVu50XObBLDfiQ.jpeg" /></figure><p>DreamBooth’s authors proposed a solution for these two issues — a class-specific prior-preservation loss. Essentially this means that while the model is training it will try learn from our images as well as images from the original class noun as the same time. It is recommended that 200 x 200 images should be sampled for each training image we use.</p><p>One final point to mention is that Cerebrium has build their fine-tuning Stable Diffusion pipeline using LoRA (Low Rank Adaptation) which offers the following benefits:</p><ul><li>The model is less likely to have catastrophic forgetting because the previous pre-trained weights are kept frozen</li><li>LoRA weights have fewer parameters than the original model and can be easily portable. This leads to faster training times.</li><li>LoRA allows control to which extent the model is adapted toward new training images (supports interpolation)</li></ul><h4>Quick Tips</h4><p>Below are some quick tips in order to get the most of your training that we have experimented with.</p><ol><li>Users have had most success with 10–12 images.</li><li>Make sure to crop your training images to a square since images are automatically scaled down to 64x64.</li><li>If your number of training iterations is too low, the model will underfit the subject’s images and won’t be able to reproduce it accurately during inference. If it’s too high, the model will overfit instead, making it unable to reproduce the subject with expressions, poses, or contexts outside of those in the training subset. A rule of thumb that has shown good results in our experiments is to use between 100 and 200 iterations per training image.</li><li>The guidance scale is a float that controls how much importance is given to the input text prompt. Lower values of this parameter will allow the model to take more artistic liberties and so we would want a high value for our user case</li></ol><h4>Tutorial</h4><p>To start, you will need to install the Cerebrium framework</p><p>pip install --upgrade cerebrium</p><p>We will then create out base project for stable diffusion with the following line:</p><p>cerebrium init-trainer diffuser ./config.yaml</p><p>This initialises a new diffuser training project where the configuration is stored in the config.yaml file</p><p>Update your config.yaml file based on the tips on the section, Quick Tips, above</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/503bad82d3b85048b2f0d27123650b15/href">https://medium.com/media/503bad82d3b85048b2f0d27123650b15/href</a></iframe><p>Cerebrium will then start a job which you can track the training logs of using the command:</p><p>cerebrium get-training-logs &lt;JOB_ID&gt;</p><p>Once the model has completed training you should receive a email. You can then run the following command to download your model weights and use them in your deployment:</p><p>cerebrium download-model &lt;JOB_ID&gt;</p><p>Using our models weights we can then deploy of model for inference with the following <em>main.py. </em>Make sure you list the required libraries in your requirements.txt.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab2668b07a8eb3fa0544602e7f83432b/href">https://medium.com/media/ab2668b07a8eb3fa0544602e7f83432b/href</a></iframe><p>We then deploy our model using the following line of code:</p><p>cerebrium deploy fine-tuned-sd --hardware A10</p><p>Once your model has been deployed we then make the following curl request:</p><p>curl — location — request POST ‘<a href="https://run.cerebrium.ai/v2/p-xxxx/fine-tuned-sd/predict&#39;">https://run.cerebrium.ai/v2/p-xxxx/fine-tuned-sd/predict&#39;</a> \ — header ‘Authorization: public-xxxxxxx’ \ — header ‘Content-Type: application/json’ \ — data ‘{“prompt”: “A professional headshot photo of a CerebriumCEO man. close-up RAW photo, sharp focus, ultra-high pixel detail, intricate, realistic, movie scene, cinematic, high-quality, full colors, incredibly detailed, 4k, 8k, 16k, hyper-realistic, RAW photo, masterpiece, ultra-detailed, professionally color graded”, “negative_prompt”: “cartoon, anime, 3d, painting, b&amp;w, worst quality, low quality, normal quality, low-res, skin spots, acne, skin blemishes, age spots, ugly, duplicate, morbid, mutilated, mutated hands, poorly drawn hands, blurry, bad anatomy, bad proportions, extra limbs, disfigured, missing arms, extra legs, fused fingers, too many fingers, unclear eyes, low-resolution, bad hands, missing fingers, bad hands, missing fingers, cartoon, low poly, text, signature, watermark, username”}’</p><p>You will see that the generated images will have some potential deformities around fingers, eyes, teeth etc. You can read the article <a href="https://stable-diffusion-art.com/know-these-important-parameters-for-stunning-ai-images/">here</a> on some potential techniques to resolve it but one important one is to implement a model like Codeformer post model generation. You can test it <a href="https://huggingface.co/spaces/sczhou/CodeFormer">here</a> however the implementation is out of scope for this tutorial.</p><p>Voila! We now have a fine-tuned Stable diffusion model that can generate images around our CEO, Michael.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9kz1VO7gw2G7uFrUc0_8A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*l-UsC6DNiI1WBmd0q5mN_w.png" /><figcaption>Orginal Image (left) Generated Image (right)</figcaption></figure><p>There are many more optimizations we could have done to our model such as better quality images, make use ofin-painting etc however it was out of scope for this article. We recommend looking at the many resources on <a href="https://stable-diffusion-art.com/">stable-diffusion-art.com</a> to improve your generated images.</p><p>You should now be fully equipped to fine-tune Stable Diffusion models around any object or person you like. Fine-tuning is a craft, nuanced with its quirks and tricks and so we recommend and experimenting with many different types of image and hyper-parameter configurations in order to get the best results. Cerebrium makes the end-to-end process of fine-tuning easy and accessible to anyone and so we are very excited to see what the community builds! Please tag us in your image generations so we can share it with our community</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c59d2e3cd3c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-tuning and deploying a LLaMA-based support bot with Cerebrium and LLamaIndex]]></title>
            <link>https://cerebriumai.medium.com/fine-tuning-and-deploying-a-llama-based-support-bot-with-cerebrium-and-llamaindex-28eb59a0a280?source=rss-3e2acdad466b------2</link>
            <guid isPermaLink="false">https://medium.com/p/28eb59a0a280</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <dc:creator><![CDATA[Cerebrium]]></dc:creator>
            <pubDate>Mon, 17 Jul 2023 12:39:13 GMT</pubDate>
            <atom:updated>2023-07-17T12:41:22.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37dGmJrH1qrTtBtxkU3UBg.png" /></figure><p>Fine-tuning has many benefits over using closed source models from OpenAI, Anthropic and other providers. Businesses see benefits such as lower latencies, lower cost per generation, the ability to handle edge cases as well as the ability to know what is going on inside the model so you can optimize it. Allowing users to fine-tune open-source models has been one of our most widely requested features at Cerebrium and so the team has been working hard to get this in the hands of users</p><p>In this tutorial we are going to showcase how we used the Cerebrium fine-tuning capability to fine-tune a LLaMA based model to create a Cerebrium customer support chat bot.</p><h3>1. Dataset Curation for Fine-tuning:</h3><p>The foundation of a good AI model often hinges on the dataset it uses for learning and fine-tuning. The primary goal in this process is to generate a dataset that encapsulates the nature of our customer queries and tries to teach the model how it should extract data from context and how it should respond based on the nature of the question and the information at its disposal. One of the big misconceptions about fine-tuning is that you should fine-tune specific information into a model — this is not correct.</p><blockquote>You want to teach the model how to handle certain use cases and how to present information to the user based on the context and the question the user asked.</blockquote><p>Information around a product or business will most likely always be changing and so to continuously fine-tune a model is infeasible. Rather up-to-date information should be injected into the context for a model to use. Additionally, information around your use-case can be sensitive and so you wouldn’t want it to be engrained into the model and accessible by all but rather injected for those that have clearance. Lastly, most foundational models are trained on a trove of diverse data and so its unlikely that if you fine-tune a model on your pricing structure that its going to forget about all previous pricing and business models it was trained on — this can lead to hallucinations.</p><h4>How we gathered our dataset</h4><p>We gathered our data from two sources:</p><ul><li>Our documentation where all files are in markdown</li><li>Our support channel in Discord. We used a Chrome plugin to download all the messages.</li></ul><p>I then built a quick script to send chunks of our Discord support messages to a GPT4 API with the following prompt:</p><p>Please create a JSON array in the following format from our Discord channel that is used to answer customer support questions:</p><pre>{&quot;prompt&quot;: {question}, &quot;completion&quot;: {completion}} where {question} is the question the user ased in the text below and {completion} is the answer to that question from the text below.<br><br>Discord messages:<br>&lt;Discord messages&gt;</pre><p>This is a very easy way to start with an initial dataset that you can go through and make sure the prompt/completion pairs are correct.</p><h4>Dataset Preparation</h4><p>In order to quickly find and set the relative context that our answers could have come from. I used LLamaIndex to chunk our documentation into a vector database and looped through the JSON dataset above to find the passages of text most similar to the completion parameter.</p><p>Your dataset should now look like:</p><pre>[{<br>    &quot;prompt&quot;: &quot;What is Cerebrium?&quot;,<br>    &quot;completion&quot;: &quot;Cerebrium is an AWS Sagemaker alternative providing all the features you need to quickly build an ML product. We provide serverless compute and infrastructure as well as try abstract as much of the latest research so you can build ML based solutions without the hassle.&quot;,<br>    &quot;context&quot;: &quot;Cerebrium is an AWS Sagemaker alternative providing all the features you need to\nquickly build an ML product.\&quot;\n---\n\nOur goal is to help companies create value through machine learning as quickly and as painlessly as possible by abstracting away a lot of the complexity and mundane infrastructure setup.\n\nSagemaker is feature rich, so we are developing the most requested functionality\nweekly based on your feedback. You can send us feedback requests at\n[support@cerebrium.ai](support@cerebrium.ai)\n\n## How we do this\n\n- &lt;b&gt;\n    &lt;u&gt;Infrastructure&lt;/u&gt;\n  &lt;/b&gt;\n  We abstract away all of the complexity around infrastructure so you don&#39;t have\n  to worry about CPUs/GPUs, Kubernetes, queues, monitoring, scaling etc. We take\n  care of this to create a robust and seamless developer experience.\n- &lt;b&gt;\n    &lt;u&gt;Research&lt;/u&gt;\n  &lt;/b&gt;\n  We try to implement the latest research towards your model as best we can in\n  order for you to deliver the best experience to your users. We automatically implement\n  quantization, LoRA, pruning and many more techniques to get your model to run faster\n  and cheaper without sacrificing performance.\n\n## Our users favorite features\n\n- \\&lt;30 second cold-start times\n- Wide variety of GPUs\n- Automatic scaling from 1 to 10k requests in \\&lt;15s\n- Define pip/conda container environments\n- Secrets manager\n- One-click deploys\n- Monitoring tool integration\n\n&lt;b&gt;All of this in just a few lines of code!&lt;/b&gt;\n\nTo get started, head to our [installation page](/installation)&quot;<br>},....</pre><p>You should go through the dataset to make sure that the context relates to the completion and that the answer is indeed hidden in the context. If the answer cannot be found in the context, I recommend you handle the use case accordingly:</p><pre>{<br>    &quot;prompt&quot;: &quot;How can I apply for the unlimited service if I want to use it?&quot;,<br>    &quot;completion&quot;: &quot;Please contact a member of the Cerebrium team @Cerebrium Team&quot;,<br>    &quot;context&quot;: &quot;Cerebrium has 3 pricing plans.\nHobby: This is a free plan and you only pay for compute. You are only allowed to deploy 3 models maximum and can only have 5 max concurrent GPU workers.\nStandard: Deploy unlimited models and have up to 30 concurrent GPU workers. This plan costs $100 a month + compute.\nEnterprise: Contact us so we can understand your requirements better but essential you get dedicated support, unlimited GPU concurrency etc.&quot;<br>},</pre><p>Here is an example of a user asking how they can get access to our enterprise plan however the context we were able to retrive is just the details of our 3 pricing plans — therefore there is no information in the context to answer this question. We are trying to teach the model to respond with “Contact the Cerebrium team” since it cannot answer the question based on the given context</p><p>There are a few more steps we can take to curate our dataset even more by asking questions in different formats. Now that the dataset is curated, let’s train our model.</p><h4>2. Fine-tuning and deploy LLaMA model using the Cerebrium</h4><p>With our refined dataset in hand, we can move on to fine-tuning our LLaMA model. The Cerebrium platform makes this extremely easy, requiring me to only specify my training parameters and takes care of dataset validation and all infrastructure. We use the default training configuration found <a href="https://docs.cerebrium.ai/cerebrium/fine-tuning/language-models/config">here</a> and the following prompt template</p><pre>prompt_template:<br>    &quot;description&quot;: &quot;Template for Cerebrium Support bot&quot;<br>    &quot;prompt_input&quot;: &quot;Below is an question paired with an input that provides further context. Write a response that appropriately answers the question. Only use information from the context. If you can&#39;t answer a question from the context, ask the user to ask for help from the Cerebrium team.\n\n### Question:\n{instruction}\n\n### Input:\n{input}\n\n### Response:\n&quot;<br>    &quot;prompt_no_input&quot;:  &quot;### Your Question:\n{instruction}\n\n### Response:\n&quot;<br>    &quot;response_split&quot;: &quot;### Response:&quot;<br>instruction_column: &quot;prompt&quot;<br>context_column: &quot;context&quot;</pre><p>We use our own prompt template to train that specifies that if the model cannot answer the question from the provided context, it should tell the user to contact the Cerebrium team.</p><p>To kick of the training job we run the following command:</p><p>cerebrium train — config-file ./config.yaml</p><p>Your training job should start and you can run the following command to see your training logs:</p><p>cerebrium get-training-logs &lt;JOB_ID&gt;</p><p>should see the following output in your terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xPXMlRS3k2wWuRWXRDbpA.png" /></figure><p>You will be notified via email once the training job has completed and then you can run the following code snippet to download your model checkpoint files</p><p>cerebrium download-model &lt;JOB_ID&gt;</p><p>To deploy this model to Cerebrium you can look at the example <a href="https://github.com/CerebriumAI/examples/tree/master/13-deploy-finetuned-adapters">here</a>. A LLaMA model isn’t the quickest so you can look at implementing the <a href="https://github.com/vllm-project/vllm">vllm</a> framework to speed up inference time to ~0.9 tokens per second on a A10 which is 24x faster than the base LLaMA model.</p><h4>3. Using LLamaIndex for Documentation Chunk Data:</h4><p>Now that our fine-tuned LLM is completed, we will need information from our documentation to aid its responses ie: the context. We chose to use <a href="https://www.llamaindex.ai/">LLamaIndex</a> for this as its extremely easy to setup and has a wide variety of integrations and functionality. It allows us to chunk relevant data from our documentation and then input it into the context of our fine-tuned LLM. Essentially, LLamaIndex simplifies the process of retrieving the right data at the right time, and ensuring the chatbot’s responses remain accurate and informed.</p><p>You can install LLamaIndex using pip install llama-index . We then have the following snippet of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d2ca1dfdb5c7ea0d6ef28c166022e8f/href">https://medium.com/media/3d2ca1dfdb5c7ea0d6ef28c166022e8f/href</a></iframe><p>Two things to notice:</p><ol><li>All our documentation files that are in markdown format are located in the data/ folder. LLamaIndex recursively goes through the entire directory and chunks all the documents to store in a vector store.</li><li>I didn’t only chunk our documentation into LLamaIndex but also the question+completion from the support channel that is not contained in our documentation so it can be used for future questions.</li></ol><p>LLamaIndex then allows you to connect your LLM deployed on Cerebrium to the vector store and therefore you can run the following code to get answers to your questions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29e88a680db4418610875b1b39d2d007/href">https://medium.com/media/29e88a680db4418610875b1b39d2d007/href</a></iframe><p>What is happening in the above code is:</p><ol><li>You are creating your Cerebrium endpoint where you deployed your model.</li><li>You are creating a vector store on all your previous support messages and documentation. As well as setting the default LLM for the vector store to be Cerebrium.</li><li>Lastly, you are asking it a question and retrieving the answer.</li></ol><p>As you can see our result is pretty accurate! There are many improvements we could still make to this such as including stop tokens in our training dataset and deployment, fine-tuning a model such as Vicuna in order to get a large speedup etc but this is out of scope for this article.</p><p>In this tutorial we have been able to show a simple way to use Cerebrium to fine-tune and deploy a LLM with just a few lines of code. Its important to remember that you don’t necessarily want to fine-tune information into a model but rather characteristics you would like it to adhere to. If you are looking to lower latency, save on costs, or if you don’t want to share your data with OpenAI fine-tuning is a great alternative to go forward with!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28eb59a0a280" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Open-Source Is the Lifeblood of Machine Learning’s Future]]></title>
            <link>https://cerebriumai.medium.com/why-open-source-is-the-lifeblood-of-machine-learnings-future-64f0683c2bc3?source=rss-3e2acdad466b------2</link>
            <guid isPermaLink="false">https://medium.com/p/64f0683c2bc3</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[future-of-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <dc:creator><![CDATA[Cerebrium]]></dc:creator>
            <pubDate>Fri, 30 Jun 2023 02:05:37 GMT</pubDate>
            <atom:updated>2023-06-30T02:06:28.641Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KIXQv9a8zuZl1qaLau817g.png" /></figure><p>As my team and I build <a href="https://www.cerebrium.ai/">Cerebrium</a>, the question that I constantly receive from customers, investors, and machine learning enthusiasts alike isn’t simply a matter of design decisions and our product differentiation. Rather, it’s a strategic crossroad: Will the future of machine learning, currently synonymous with LLMs and Generative Models, revolve around the rule of a few dominating models, or could we find a constellation of finely-tuned, diverse models?</p><p>Rising from this debate, an even more complex question forms: Where should we stand on the open-source versus closed-source battle lines? These aren’t just theoretical questions — at Cerebrium we like to think we will be thought leaders in this space and so the direction we choose will help shape the next revolution of this technology.</p><p>In an interesting article by Clemens Mewald, the Head of Product at Instabase, titled “<a href="https://medium.com/towards-data-science/the-golden-age-of-open-source-in-ai-is-coming-to-an-end-7fd35a52b786">The Golden Age of Open Source in AI is coming to an end</a>”, he mentions some very interesting points, namely:</p><ol><li>Companies are releasing open-source models under more restrictive licenses since they are deterred by the fact that others might have more commercial traction than them. For example, OpenAI open-sourced GPT-2 but won’t do the same for GPT-3 and GPT-4 due to competition and the need to gain commercial traction.</li><li>Researchers prefer to work in places where their work can be published so they can be recognised by industry in order to command higher salaries (and clout). This was prevalent with the team from Mistral AI where one of the founders was the Team Lead for the LLaMA model from Meta and was one of the main reasons they were able to raise an <a href="https://techcrunch.com/2023/06/13/frances-mistral-ai-blows-in-with-a-113m-seed-round-at-a-260m-valuation-to-take-on-openai/">$113 million seed round</a>.</li></ol><p>While I agree with most of the above, I still see a world in which open-source machine learning is a core part of the growth and innovation. I have four thoughts on this:</p><h4>1. Open-source and closed source won’t be mutually exclusive!</h4><p>A simple example I like to refer to is to the early 1990’s, the start of the internet. Netscape, AOL and Yahoo made the internet popular by making it accessible and useful and in turn used their commercial traction to fund the research and development of some of the most impressive technologies and products today. However, the TCP/IP protocol and Apache HTTP server were open-source developments that without which, companies like Netscape and Yahoo, may have never existed or had the impact they did.</p><p>The majority of large language models today are built on the transformers architecture, which was first detailed by Google in 2017. If they did not publicly release their paper, “Attention is all you need”, then we would most likely not be experiencing the growth in LLM’s we see today. I suspect Google will continue to release new research consistently. However, they will leverage their expertise and team to create commercially beneficial applications and nuances in their products.</p><p>Without the potential for a large impact and commercial traction, how can we expect to fund this research and innovation industry-wide, — after all, doesn’t monetary gain prove value?</p><h4>2. Can Open-source and Closed-source models coexist?</h4><p>Yes they can — shown above they are two sides of the same coin. This has been proven with software today, and there are numerous benefits and shortcomings to both.</p><p>Closed-source solutions, like OpenAI’s GPT4, offer an easily accessible LLM to a broad user base, demonstrating impressive versatility across a range of applications. However, it can’t handle 100+ languages with the same performance; it can’t handle mathematical and physics use cases well; and lastly, it is very non-deterministic. These make GPT4 unsuitable for a large proportion for many industries.</p><p>Open-source models allow for flexibility, accessibility, innovation, security, and explainability, all of which are extremely important for companies operating in the enterprise space. It is also important to note that even though these models are open-source, the community of contributors can be a moat and offering a managed service of this product or extra paid features can be commercially viable.</p><p>Open-source platforms such as GitHub and Docker are doing $1 billion and $135 million in annual revenue. They are based off popular open-source projects but are able to offer managed services on top of this in order to gain revenue.</p><h4>3. Why multiple, finely-tuned Models will Outweigh a Few dominating models?</h4><p>The generalised, multi-purpose monoliths like GPT4, while impressive, have their limitations — they might struggle to manage hundreds of unique use cases, especially in the world’s extensive array of languages. These all-encompassing models will strive for mass consumer use cases yet, they will underperform when it comes to offering specialised solutions tailored to specific business needs. Being a multi-purpose model adds to the complexity - size, cost, data requirements as well as longer latency times however this could become mute as new research is developed and deployed.</p><p>At Cerebrium, we have seen many customers use multiple models in their workflows, both off the shelf as well as fine-tuned, that improve the functionality of their use case. Fine-tuned models are cheaper, faster and perform better when built for certain use cases. Additionally, business requirements differ based on their industry, size, consumers profiles, data at their disposal, process flows, geographic location etc. Foundational models will be like web frameworks (React, Next.js, Vue) however, the way that companies implement them, fine-tune them and stitch it all together will be very different. This will be the technology differentiator for most businesses.</p><h4>4. Open-source is the quickest way to meet ML engineer demand</h4><p>Machine learning is a discipline that requires understanding across mathematics/statistics, chip infrastructure and software. This makes it a difficult and complex discipline to understand. It is estimated there are ~500,000 machine learning engineers and researchers and 25 million software developers worldwide. In order to maintain the pace of innovation, we simply cannot afford to wait for another half-million ML engineers to surface over the next three years. Instead, it’s crucial to empower our vast community of software engineers to harness the wealth of available research and turn it into accessible, practical solutions.</p><p>Additionally, if we had to continue in a closed source manner, every industry would be affected piecewise instead of in parallel. Industries with the largest number of experts would evolve first, as well as industries in which the largest monetary gain could be realised. If our goal is to create impact industry-wide in the shortest time possible, then enabling as many people as possible to build with machine learning advancements is the only way to do that — this is one of our North stars at Cerebrium;.</p><h4>5. A new business model for a new platform shift</h4><p>With each significant technological breakthrough come new, innovative business models. A relevant example is the pivotal move of businesses requiring on-premise infrastructure to leveraging the cloud. Businesses transitioned from large upfront expenses to usage-based pricing, which allowed technologies to be more accessible and allowed the business to have a larger Total Addressable Market (TAM) from day one.</p><p>One of the areas I think we will see business model innovation in is in contribution-based pricing — users and companies will be priced based on the cost of contributions of multiple stake holders to build the underlying product. Contributions in the form of raw data, curated and bespoke models, licenses, and even the underlying infrastructure itself, will help push the industry into a not only being more performant and useful, but also more democratised and accessible.</p><p>With a pricing model that resembles something of this nature, open-source models could be compensated for their contributions, and therefore researchers and research labs alike would have an incentive to release their work.</p><p>In closing, as an engineer, I tend to always be on the side of open-source. However as an entrepreneur I also see the value in commercial traction and creating some proprietary software. There are still many questions to be answered and as we progress some of the points above might age badly. However, based on what I have seen companies implement in production, the decision making process behind the technologies they are using and the use cases that are providing real tangible value, there is still a lot of work to do and the only way to get there is in a combination of open-source and closed source development.</p><p>In conclusion, my perspective as an engineer naturally gravitates towards open-source. Yet, as an entrepreneur, I recognise the commercial relevance and the need for proprietary software. The open-source vs. closed-source debate is complex, ever-evolving, and many questions remain to be answered. Nevertheless, one thing I believe is: the future of machine learning will require embracing both open-source and closed-source development. Through that delicate balance, we can keep up with demand, foster innovation, and build tools that will drive tangible benefits to diverse use-cases. We have a lot of rewarding work ahead of us at Cerebrium so if you are interested, please reach out — we are hiring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64f0683c2bc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding LLaMA: A Deep Dive into Large Language Model Meta AI]]></title>
            <link>https://cerebriumai.medium.com/understanding-llama-a-deep-dive-into-large-language-model-meta-ai-9977030777b9?source=rss-3e2acdad466b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9977030777b9</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[meta]]></category>
            <category><![CDATA[meta-llama]]></category>
            <dc:creator><![CDATA[Cerebrium]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 16:13:24 GMT</pubDate>
            <atom:updated>2023-06-09T16:13:40.028Z</atom:updated>
            <content:encoded><![CDATA[<p>LLaMA, or Large Language Model Meta AI, stands as a significant milestone in the research landscape of natural language processing (NLP). Developed by the FAIR team of Meta AI from December 2022 to February 2023, this innovative auto-regressive language model, founded on a transformer architecture, exhibits a transformative step in the evolution of AI technology.</p><p>LLaMA comes in various sizes — 7B, 13B, 33B, and 65B parameters — to accommodate different research needs and computational capacities. LLaMA can be used for tasks like report drafting, creative content generation, customer support, and developing interactive AI assistants. With its strong contextual understanding and ability to deliver nuanced responses, LLaMA has the potential to disrupt industries across healthcare, entertainment, and education.</p><p>LLaMA is one of many language models you can run on Cerebrium. Cerebrium empowers developers to deploy ML models with a minimal amount of code, reducing complexity and increasing efficiency. In our upcoming articles, we will demonstrate how to deploy LLaMA using Cerebrium and HuggingFace, while also exploring techniques for monitoring its performance and investigating different LLaMA implementations available on HuggingFace, including a comparison with Bard and GPT4.</p><h3>Intended Use</h3><p>The primary intention behind LLaMA is to facilitate research on large language models. This includes exploring potential applications such as question answering and natural language understanding, comprehending the capabilities and limitations of current language models, evaluating and mitigating biases, and understanding the risks associated with toxic and harmful content generation. LLaMA serves as a valuable tool to help developers and researchers in the fields of NLP, machine learning, and artificial intelligence to advance their knowledge and expertise in language processing.</p><p>LLaMA can be used for linguistic analysis, algorithm development, and language modeling. Its versatility allows researchers to apply it to various research areas and tasks, enabling new discoveries and driving progress in the field. By leveraging LLaMA, researchers can conduct in-depth investigations, establish performance benchmarks, and contribute to the ongoing development and improvement of language models.</p><p>Meta notes that LLaMA, as a foundational model, is primarily intended for research purposes and requires careful evaluation before application in practical settings. They recommend exercising caution to avoid potential pitfalls, such as biases, offensive content generation, and dissemination of incorrect information.</p><h3>Training and Evaluation Factors</h3><p>The training data for LLaMA was collected from a variety of sources: CCNet (67%), C4 (15%), GitHub (4.5%), Wikipedia (4.5%), Books (4.5%), ArXiv (2.5%), and Stack Exchange (2%). This makeup contributes significantly to the model’s comprehensive understanding of language styles and domains. With the inclusion of 20 languages, predominantly English, LLaMA exhibits a robust performance across multilingual applications, critical for global platforms.</p><p>The variety in data sources also means that LLaMA taps into a rich knowledge base, with academic articles from ArXiv providing technical insights, GitHub entries offering a glimpse into coding practices, and Wikipedia articles presenting a general overview of a vast array of topics. This collective diversity fuels LLaMA’s versatility and expansive applicability.</p><h3>Model Performance Measures</h3><p>LLaMA’s performance is evaluated across a range of metrics, each assessing different aspects of the model’s capabilities. Let’s look at what these metrics tell us in comparison to other similar large language models:</p><ul><li><strong>Accuracy for common sense reasoning, reading comprehension, natural language understanding (MMLU): </strong>These metrics test the model’s ability to understand and infer information from text input. Higher accuracy in these areas generally indicates a model with better comprehension and reasoning abilities. In tasks like BoolQ, PIQA, SIQA, and MMLU, LLaMA’s performance improves with increasing model size, showing competitive performance compared to other large-scale models.</li><li><strong>Exact match for question answering: </strong>This metric measures the model’s ability to produce the exact correct answer to a question. The larger LLaMA models show competitive results in this aspect, particularly in scientific question-answering tasks like ARC-e and ARC-c, often outperforming smaller models.</li><li><strong>The toxicity score from Perspective API on RealToxicityPrompts: </strong>This metric evaluates the potential for the model to generate harmful or offensive content. Although specific scores aren’t provided, the developers have prioritized reducing such outputs, which is an essential aspect of model development in order to ensure safe and responsible usage.</li></ul><p>These evaluations were carried out using standard benchmarks, which you can read more about in the <a href="https://ai.facebook.com/blog/large-language-model-llama-meta-ai/">official documentation</a>.</p><p>Comparatively, LLaMA’s strengths lie in its ability to accurately infer information and answer questions, particularly in scientific domains. The increased performance of larger LLaMA models suggests scalability is a factor in enhancing its capabilities. As for improvements, while efforts have been made to limit offensive content, continual refinement in this area would make LLaMA more reliable for wide-scale deployment. After all, a robust AI model should not only be proficient in task completion, but also uphold ethical standards.</p><h3>Hyperparameters and Quantitative Analysis</h3><p>The configuration of the LLaMA model’s hyperparameters plays a crucial role in achieving optimal performance for specific use cases. The hyperparameters of each variant of the LLaMA model are summarized in the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f4oZGF7zUUusQBhu" /><figcaption><em>Table 1 — Summary of LLaMA Model Hyperparameters (</em><a href="https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md"><em>source</em></a><em>)</em></figcaption></figure><p>Let’s delve into the key hyperparameters and how they impact the model:</p><ul><li><strong>Number of Parameters:</strong> The model’s total number of learnable weights and biases determines its capacity to handle complex tasks. Larger models with more parameters exhibit enhanced performance. However, selecting the appropriate model size must consider the computational resources required for training and inference.</li><li><strong>Dimension:</strong> The dimension hyperparameter defines the size of the embedding space in the model. It influences the richness of the learned representations and directly affects the model’s ability to capture intricate features. Larger dimensions benefit tasks that require fine-grained semantic understanding, while smaller dimensions suffice for simpler tasks.</li><li><strong>Number of Heads (n heads):</strong> The transformer architecture-specific hyperparameter denotes the number of separate learned linear transformations in the multi-head attention mechanism. Increasing the number of heads empowers the model to capture diverse dependencies and improve performance. However, it also introduces higher computational complexity.</li><li><strong>Number of Layers (n layers): </strong>The depth of the neural network relies on the number of layers. Deeper networks can model complex features and hierarchical representations. However, training deeper models poses challenges, requiring larger datasets and longer training times.</li><li><strong>Learning Rate: </strong>The learning rate controls the magnitude of parameter updates during training. A higher learning rate facilitates faster convergence, but risks overshooting the optimal solution. Conversely, a lower learning rate enhances stability but demands more training iterations for convergence. Adjusting the learning rate is critical for achieving optimal performance on the given dataset.</li><li><strong>Batch Size: </strong>The batch size determines the number of examples processed by the model before updating its parameters. Larger batch sizes enable more efficient training through parallel processing but demand more memory. Smaller batch sizes enhance generalization but can prolong the training process. Selecting the batch size depends on available computational resources and dataset characteristics.</li></ul><p>By carefully selecting and fine-tuning these hyperparameters, users can tailor the LLaMA model to their specific use cases, ensuring optimal performance and resource utilization.</p><p>In addition to hyperparameter configuration, quantitative analysis provides insights into LLaMA’s performance across various reasoning tasks. The table below shows LLaMA’s performance against several standardized reasoning tasks, which you can read more about <a href="https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DrZfd5E-cTXLpNFt" /><figcaption><em>Table 2 — Summary of LLaMA Model Performance on Reasoning Tasks (</em><a href="https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md"><em>source</em></a><em>)</em></figcaption></figure><p>Comparing the performance of different LLaMA variants reveals that larger models generally outperform smaller ones, highlighting the benefits of increased model size. However, it’s crucial to consider the trade-off between performance gains and the computational resources required for training and utilizing larger models.</p><p>In summary, this kind of quantitative analysis serves as a valuable reference for users, empowering them to make informed decisions when selecting the most suitable LLaMA variant for their specific use cases. By considering the desired trade-off between model performance and resource constraints, you can make well-founded decisions that align with your requirements.</p><h3>Conclusion</h3><p>The LLaMA model, with its variety of model sizes and capacities, holds a notable place in the evolving sphere of AI and NLP. Its proficiency is reflected in its performance across a series of tasks such as common sense reasoning, reading comprehension, and natural language understanding. These results are significant as they demonstrate LLaMA’s capabilities compared to other large language models in the AI community.</p><p>The model serves as a valuable tool for researchers and developers working in NLP, offering applications in question answering, text understanding, evaluating biases, and mitigating risks of toxic content. With competitive performance in reasoning tasks and question answering, LLaMA’s versatile design and adjustable hyperparameters enable researchers to drive advancements in NLP research. As LLaMA continues to evolve, it holds great potential to shape the future of AI technology and unlock new insights into language understanding and generation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9977030777b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customizing the Prompt for Img2Img Model: Techniques for Guiding Image Generation]]></title>
            <link>https://cerebriumai.medium.com/customizing-the-prompt-for-img2img-model-techniques-for-guiding-image-generation-8deaf74f0353?source=rss-3e2acdad466b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8deaf74f0353</guid>
            <category><![CDATA[stable-diffusion]]></category>
            <category><![CDATA[img2img]]></category>
            <category><![CDATA[generative-ai]]></category>
            <dc:creator><![CDATA[Cerebrium]]></dc:creator>
            <pubDate>Mon, 22 May 2023 18:29:09 GMT</pubDate>
            <atom:updated>2023-05-22T18:29:09.529Z</atom:updated>
            <content:encoded><![CDATA[<p>In previous guides, we learned about how the Img2Img model works, how to deploy it, and how to monitor its performance. In this guide, we’ll examine how to craft excellent prompts to get the most out of the model.</p><p>Customizing the text prompt is akin to steering the model toward your desired output. It’s your primary means of communication with the model, serving as a guide that influences every pixel in the generated image. A well-crafted prompt can be the difference between a chaotic, disconnected image and a beautiful, coherent scene that precisely captures your intended vision.</p><p>This guide is here to help you master the art and science of prompt customization. We’ll delve into the role of the text prompt, explore a variety of techniques for customizing it, and discuss strategies for optimizing your prompts for desired outputs. By the end, you’ll have a solid understanding of how to communicate effectively with the Img2Img model and guide it towards generating the images you envision.</p><p>So, buckle up and prepare to unlock the full potential of the Img2Img model.</p><h3>Understanding the Role of the Text Prompt</h3><p>Think of the text prompt as the conductor of an orchestra, guiding and shaping the performance of the model. The prompt conditions the model to generate images that align with the provided textual cues.</p><p>We can’t overstate the importance of specificity and clarity in the text prompt. The more precise and detailed the prompt, the more refined the output. Consider it this way — if you tell an artist to “draw a dog,” you could end up with any kind of dog in any setting. However, if you ask for “a Golden Retriever playing fetch in a sunlit park,” you provide a much clearer vision, which is likely to result in a more satisfying artwork.</p><h3>Techniques for Customizing the Prompt</h3><p>Now, let’s get our hands dirty and dive into the techniques to customize prompts for the Img2Img model. In this guide, we’ll be using this famous portrait (“Girl with Pearl Earring” by Johannes Vermeer) as an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*c_mw6Z6LPGG7c-q0.jpg" /><figcaption><em>Example: Girl with Pearl Earring by Vermeer</em></figcaption></figure><h4>Providing explicit visual instructions</h4><p>Being descriptive with your language is key to guiding the model. For instance, “a starry night over a serene lake” is more likely to generate a desired output than merely “a night scene.” You can also specify visual attributes, composition, or style — think “a medieval castle on a hill, rendered in a watercolor style.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*KMmGzdcHprbK-5ql.png" /><figcaption><em>Prompt: “girl with pearl earring in a pop art style”</em></figcaption></figure><h4>‍Incorporating textual cues or concepts</h4><p>You can guide the model further by embedding keywords or phrases in the prompt, like “sunset,” “cherry blossom,” or “Art Nouveau style.” Another approach is to use semantic relationships or analogies — for example, “an owl with the majesty of a king.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*GD9O4ZsrObd5_RuT.png" /><figcaption><em>Prompt: “girl with pearl earring, beaming as if on a beautiful sunny day”</em></figcaption></figure><h4>‍Experimenting with prompt variations</h4><p>Don’t hesitate to refine and iterate on your prompts. Experiment with different structures, formats, or even the order of words. Who knows? Swapping “a serene lake under a starry night” for “a starry night over a serene lake” might just give you that masterpiece you’ve been after.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*V6Hb4gz7Z0PMTlLu.png" /><figcaption><em>Prompt: “girl with pearl earring underneath a surreal and peaceful starry sky”</em></figcaption></figure><h4>‍Optimizing the Prompt for Desired Outputs</h4><p>Creating an effective prompt is all about striking a balance between specificity and flexibility. If your prompt is too vague, say, “a landscape,” the model could generate anything from a desert scene to a cityscape. While this might be useful in some contexts, more often than not, you’ll want to guide the model to produce a specific output.</p><p>On the other hand, if your prompt is overly specific, such as “a clear day in Central Park in New York City with a green bench in the foreground and the Statue of Liberty visible between the trees in the background,” you might end up stifling the model’s creativity. The output could become predictable, and the image might lack the spontaneous elements that can make generative art so intriguing.</p><p>A well-optimized prompt will provide enough detail to guide the model while leaving some room for creative interpretation. For instance, “a city park on a sunny day with a notable landmark visible in the background” gives the model direction while allowing for some flexibility in the interpretation of the scene.</p><p>One way to adjust the level of guidance you provide to the model is by using the guidance scale parameter available in certain frameworks like<a href="https://www.cerebrium.ai/"> Cerebrium</a>. This parameter can be adjusted to increase or decrease the influence of the prompt on the generated output. For example, a lower guidance scale value could result in more diverse and potentially surprising results, while a higher value would make the model stick more closely to the prompt.</p><p>Iterative adjustment of the prompt based on model outputs is another technique to optimize your results. This process, akin to a feedback loop, involves generating an image, assessing its alignment with your vision, refining the prompt based on your observations, and then repeating the process.</p><p>For instance, if your prompt is “a peaceful forest scene with a stream,” and the model generates an image of a dense, dark forest that feels more eerie than peaceful, you might decide to refine the prompt to “a peaceful forest scene with a sunlit stream and open canopy.”</p><p>Another strategy to achieve diverse or novel outputs is to manipulate the elements of the prompt. You can change style keywords, modify the subject, or alter the visual attributes. For instance, if you start with the prompt “a castle at sunset,” you could vary the outputs by changing the style keyword to “a castle at sunset in impressionist style,” or modifying the subject to “a castle at sunset reflected in a lake.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*F7OevND_YjP4YAJ7.png" /><figcaption><em>Prompt: “A castle at sunset in impressionist style”</em></figcaption></figure><p>‍In some cases, you might find it useful to use negative prompts to steer clear of undesired attributes. For example, if the model consistently generates images with elements you don’t want, adding “no dragons” to your prompt could help to eliminate these elements from the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*oK8TEo9aISua7DMW.png" /><figcaption><em>Prompt: “A castle at sunset reflected in a lake”</em></figcaption></figure><p>‍</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*fEmuZCEeRP5c4qlI.png" /><figcaption><em>Prompt: “A castle at sunset reflected in a lake.” Negative prompt: “Weird artifacts, pixels, smudges, blurs”</em></figcaption></figure><p>‍By understanding and applying these strategies, you can create a dynamic range of images from a single prompt, making the most of the Img2Img model’s capabilities.</p><h3>Best Practices and Considerations</h3><p>Starting simple and gradually adding complexity is a good rule of thumb. Begin with a basic prompt like “a cat” and then add details like “a black cat,” “a black cat sitting on a red cushion,” and so forth.</p><p>The prompt should also align with the use case or application. For instance, if you’re designing a poster for a sci-fi convention, a prompt like “a cyberpunk cityscape at dusk with futuristic skyscrapers” might be apt.</p><p>Leveraging pre-trained prompt templates or examples can provide a headstart. Be sure to maintain consistency and coherence between the prompt and the desired output.</p><h3>Resources and Tools for Prompt Customization</h3><p>Customizing prompts for image generation can be an intricate process. Fortunately, there is an array of resources and tools designed to make this process more efficient and more streamlined. Here’s a handy collection to get you started.</p><p>First on the list is<a href="https://www.cerebrium.ai/"> Cerebrium</a> itself. The detailed Cerebrium<a href="https://docs.cerebrium.ai/introduction"> documentation</a> serves as an excellent starting point, providing a thorough overview of the platform and step-by-step guides for deploying prebuilt models, including the<a href="https://docs.cerebrium.ai/cerebrium/prebuilt-models/image-models/img2img-stable-diffusion"> Stable Diffusion Img2Img model</a>.</p><p>If you’re in search of inspiration or wish to explore an extensive collection of prompts,<a href="https://openart.ai/promptbook"> OpenArt’s Promptbook</a> is a goldmine. Hosting over 10 million prompts, it’s a vast resource that allows you to generate AI art and images via models like Stable Diffusion and DALL·E 2.</p><p>Similarly,<a href="https://prompthero.com/"> PromptHero</a> allows you to search through millions of AI-generated images. It’s a great tool for exploring the capabilities of models like Stable Diffusion and Midjourney and seeing the kind of output your prompts could generate.</p><p>Last but not least, the<a href="https://arthub.ai/"> Arthub Prompts Library</a> is a fantastic resource dedicated to the Stable Diffusion model. It offers a plethora of prompts to explore and learn from, serving as a great starting point for anyone new to the world of prompt customization.</p><h3>Conclusion</h3><p>Customizing the text prompt is an art and a science, an indispensable tool in harnessing the power of the Img2Img model. The potential is vast — from creating unique artwork to designing game assets or even generating product designs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8deaf74f0353" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying the Prebuilt Img2Img Model with Cerebrium: A Step-by-Step Guide to Image Generation]]></title>
            <link>https://cerebriumai.medium.com/deploying-the-prebuilt-img2img-model-with-cerebrium-a-step-by-step-guide-to-image-generation-d4b1ef9d0bfa?source=rss-3e2acdad466b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4b1ef9d0bfa</guid>
            <category><![CDATA[cerebrium]]></category>
            <category><![CDATA[image-generation]]></category>
            <category><![CDATA[img2img]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <dc:creator><![CDATA[Cerebrium]]></dc:creator>
            <pubDate>Mon, 22 May 2023 14:45:42 GMT</pubDate>
            <atom:updated>2023-05-22T14:45:42.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sbjuTFYoHVLmKp_YT8xElg.png" /></figure><p>Today we’re going to dive into the world of image generation using prebuilt models with Cerebrium. The purpose of this guide is to provide a comprehensive step-by-step guide to deploying the prebuilt <a href="http://www.cerebrium.ai/blog/introduction-to-stable-diffusion-img2img-shaping-the-future-of-image-generation">Img2Img model</a> using Cerebrium.</p><p><a href="https://www.cerebrium.ai/">Cerebrium</a> is a machine learning framework that simplifies training, deploying, and monitoring of Machine learning models with just a few lines of code. Whether you’re a seasoned machine learning practitioner or a curious enthusiast, you’ll find Cerebrium’s power to deploy models like Img2Img, a game-changer.</p><h3>Background on Prebuilt Img2Img Models</h3><p>Img2Img models can generate images from an input image, providing numerous possibilities. The one we’re deploying today is the Image-to-Image text-guided generation with Stable Diffusion, a prebuilt model offered by Cerebrium. This model allows us to give a text prompt and an initial image to guide the generation of new images. Let’s see how we can do this with Cerebrium.</p><h3>Step-by-Step Deployment Guide</h3><h3>Obtain API Key and Credentials from Cerebrium</h3><p>Sign up on <a href="https://www.cerebrium.ai/">Cerebrium</a> and get your API key from your dashboard. Treat this key as your passport to the world of Cerebrium.</p><h3>Set up the Cerebrium Environment</h3><p>Install the Cerebrium Python library and set up your environment as per the instructions provided in the <a href="https://docs.cerebrium.ai/introduction">Cerebrium documentation</a>. This is your ticket to the Cerebrium universe.</p><h3>Deploy the Prebuilt Img2Img Model</h3><p>You can deploy the model directly from your dashboard or via the Cerebrium Python framework. If using python, just specify the identifier “sd-img-2-img” to indicate you want to deploy the Img2Img model.‍</p><p>Here’s a Python snippet to deploy the model:</p><pre>from cerebrium import deploy, model_type<br>endpoint = deploy((model_type.PREBUILT, &quot;sd-img-2-img&quot;), &#39;my-flow&#39;, &quot;API-KEY&quot;)</pre><p>Replace &lt;API_KEY&gt; with your actual API key.</p><h3>Prepare Input Data: Prompt and Initial Image</h3><p>The Img2Img model operates using two primary inputs: a text prompt and an initial image.‍</p><ul><li><strong>Prompt:</strong> The text prompt essentially guides the image generation process. For example, if your prompt is “a photo of a sunset over the ocean”, the model will generate images that, to the best of its ability, visually represent this description. Your choice of words in the prompt will significantly influence the final output.</li><li><strong>Initial Image:</strong> This input is optional, but it can be extremely useful for tasks like style transfer or to guide the generated images’ context. If provided, the initial image should be a base64 encoded string of your image. The model will use this image as a starting point and transform it guided by the text prompt.</li></ul><h3>Configure Deployment Parameters: Inference Steps, Guidance Scale, Variations</h3><p>To customize your image generation process, you have several tunable parameters at your disposal:</p><ul><li><strong>Num_Inference_Steps:</strong> The number of steps you’d like the model to take during the image generation process. The results typically improve with more steps, but it also increases the generation time. It defaults to 50 steps and is an optional parameter. Experiment with this to find a balance between output quality and generation speed that works for you.</li><li><strong>Guidance_Scale: </strong>This is an optional parameter, defaulting to 7.5. It influences how strongly the text prompt guides the image generation process. A higher guidance scale will force the generated images to align more closely with the prompt, potentially at the cost of image quality or diversity.</li><li><strong>Num_Images_Per_Prompt: </strong>An optional parameter that defaults to 1. It represents the number of image variations you’d like the model to generate per prompt. If you want to see multiple interpretations of your prompt, this is the parameter to adjust.</li></ul><p>‍</p><p>There are also a few more optional parameters you could play around with:‍</p><ul><li><strong>Negative_Prompt:</strong> Here’s where you can specify what you don’t want in your images. For instance, if you want an image of a landscape without any animals, you can put “animals” in the negative prompt.</li><li><strong>Seed:</strong> If you want to ensure that image generations are the same for identical prompts and images, set this parameter to a fixed integer.</li><li><strong>File_URL: </strong>For larger images, instead of a base64 encoded string, you can provide a URL where Cerebrium can fetch your initial image.</li><li><strong>Webhook_Endpoint: </strong>Specify the URL where Cerebrium can send a response confirming the generated images are ready.‍</li></ul><p>These parameters give you control over the image generation process, allowing you to customize it to your requirements. Remember, experimenting with these values is part of the fun and could lead to surprising and exciting results!</p><h3>Make the Deployment Request to Cerebrium API</h3><p>You can interact with the deployed model by sending a POST request to the endpoint provided at deployment. Make sure to include your API key in the request header for authentication. Here’s an example request from the Cerebrium docs:</p><pre>curl --location --request POST &#39;https://run.cerebrium.ai/sd-img-2-img-webhook/predict&#39; \<br>      --header &#39;Authorization: API_KEY&#39; \<br>      --header &#39;Content-Type: application/json&#39; \<br>      --data-raw &#39;{<br>        &quot;prompt&quot;: &quot;a photo of an astronaut riding a horse on mars.&quot;,<br>        &quot;image&quot;: &quot;BASE_64_STRING&quot;<br>        &quot;num_inference_steps&quot;: 50,<br>        &quot;guidance_scale&quot;: 7.5,<br>        &quot;num_images_per_prompt&quot;: 1,<br>        &quot;negative_prompt&quot;: &quot;&quot;,<br>        &quot;seed&quot;: 120,<br>        &quot;file_url&quot;: &quot;https://your-url.com/image.png&quot;<br>        &quot;webhook_endpoint&quot;: &quot;https://your-url.com&quot;<br>      }&#39;</pre><p>And here’s what an example response looks like:</p><pre>{<br>    &quot;run_id&quot;: &quot;UUID_STRING&quot;,<br>    &quot;message&quot;: &quot;Successfully generated image&quot;,<br>    &quot;result&quot;: [BASE_64_STRING]<br>}‍</pre><h3>Monitor Deployment Progress and Retrieve the Generated Images</h3><p>Upon successful image generation, Cerebrium sends the images to the webhook endpoint provided. Also, the response includes the generated images as base64 encoded strings. You can read more about monitoring the performance of the Img2Img prebuilt model and enhancing it <a href="http://www.cerebrium.ai/blog/customizing-the-prompt-for-img2img-model-techniques-for-guiding-image-generation">here</a>‍</p><h3>Conclusion</h3><p>We’ve explored how to deploy a prebuilt Img2Img model using Cerebrium. You’ve seen step-by-step how to obtain your API key to deploy the model, set the parameters, retrieve the generated images, and monitor performance. I encourage you to experiment with these deployed models. Explore the realms of image generation and uncover novel applications in your field.‍</p><p>If you need help, the <a href="https://docs.cerebrium.ai/introduction">Cerebrium documentation</a> is extensive that can help you. You can also check out our next article on how to shape your prompts and optimize them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4b1ef9d0bfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>