# Introduction

Lagrange ([lagrange.computer)](https://lagrange.computer/) is an all-in-one decentralized computing platform to store and deploy code securely, empowering developers to build web3 apps through a full suite of Web3 tooling.

Web3 developers can’t make the code hosting, deployment, testing, and running demos in one place. What’s more, they can’t take full advantage of decentralized storage and computing resources in the Web3 environment.<br>

With the Lagrange platform, developers can display applications efficiently with the support of decentralized storage and computing. Developers can also get massive traffic and revenue from in-app-purchasing on the Lagrange platform.

### Key features of Lagrange include

1. **Lagrange Space**: Enables fair and equitable storage, sharing, creation, reward, and dissemination of knowledge and development resources.&#x20;
2. **Git Style Management**: Offers a distributed version control tool, Lagrange-cli, making a local clone of the project as a complete version control space in IPFS.&#x20;
3. **Decentralized Computing Power**: Community members can rent out their computing power to researchers and users.&#x20;
4. **DApps Deployment:** Auto-deploy DApps by Dockerfile and yaml, enabling real-time testing and implementation.&#x20;
5. **Data NFT minting**: Dataset owners can tokenize their uploaded datasets on the Lagrange platform.&#x20;
6. **Decentralized Code Hosting**: Hosting of all space code in distributed IPFS by multichain storage.

<table data-view="cards"><thead><tr><th></th><th></th><th></th></tr></thead><tbody><tr><td></td><td><a href="/pages/gBKa3TNPrATRMdOMKgz8">Datasets</a></td><td></td></tr><tr><td></td><td><a href="/pages/l3NM5BFRgWa0BCAHVcsO">Models</a></td><td></td></tr><tr><td></td><td><a href="/pages/pypkN5LIgqhAKicVWLk2">Spaces</a></td><td></td></tr><tr><td></td><td><a href="/pages/gfo4MQt6YxxxyrlqBMHU">Computing</a></td><td></td></tr><tr><td></td><td><a href="https://github.com/lagrangedao/docs/blob/main/mars-testnet/README.md">Mars Testnet</a></td><td></td></tr></tbody></table>


# Getting Started

{% hint style="info" %}
**What You Need:**&#x20;

* **Gas Fees:** Gas fees are transaction fees required to execute a transaction.  For transactions on Lagrange, ETH is required.
* **Payment to Computing Providers:** You have to pay Computing Providers in `SWANC` (Swan Credit Token) to utilize their computing resources to power your Space.
  {% endhint %}

### Network Information <a href="#network-information" id="network-information"></a>

| Network Name       | Swan Chain                                                                |
| ------------------ | ------------------------------------------------------------------------- |
| RPC URL            | [https://mainnet-rpc01.swanchain.io](https://mainnet-rpc01.swanchain.io/) |
| Chain ID           | 254                                                                       |
| Currency Symbol    | ETH                                                                       |
| Block Explorer URL | [https://swanscan.io](https://swanscan.io/)                               |

If the above Block Explorer fails, please try using this one: [https://mainnet-explorer.swanchain.io](https://mainnet-explorer.swanchain.io/)

### Set Up Metamask <a href="#set-up-metamask" id="set-up-metamask"></a>

#### **Step 1: Add Swan Chain to Metamask** <a href="#step-1-add-swan-chain-to-metamask" id="step-1-add-swan-chain-to-metamask"></a>

1. Open MetaMask and click on the network selector at the top left.
2. Select "Add network" and then "Add a network manually."
3. Fill in the details for Swan Chain Mainnet following [Network Information](#network-information)

<figure><img src="https://docs.swanchain.io/~gitbook/image?url=https%3A%2F%2F3478205236-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FcvUWH8GhRCqvKwuN0BGF%252Fuploads%252Fgit-blob-5488d1234656c7f7565c8361236b69731c93f752%252Fnetwork_info.png%3Falt%3Dmedia&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=48ddbf3&#x26;sv=1" alt="" width="375"><figcaption></figcaption></figure>

1. Click "Save" or "Add" to save the network.

#### **Step 2: Import Tokens** <a href="#step-2-import-tokens" id="step-2-import-tokens"></a>

1. In Metamask, click on "Import tokens" at the bottom of the Tokens tab.
2. Enter the token contract address for SWAN Credit Token:

`0xAF90ac6428775E1Be06BAFA932c2d80119a7bd02`

1. The token symbols and decimals should autofill. If not, check the block explorer.
2. Click "Import" to confirm.

### Fund Your Wallet <a href="#fund-your-wallet" id="fund-your-wallet"></a>

**Step 1: Purchasing ETH**

Fund your wallet with ETH from any Decentralized Exchange (DEX) or Centralized Exchange (CEX).

Funding your network account is required to use the network. All transactions, including claiming Swan Credit tokens and deploying Spaces, charge a transaction fee. Ensure you have sufficient ETH to cover these costs.

**Step 2: Bridge ETH from Ethereum to Swan Chain**

Go to[ Bridge](https://bridge.swanchain.io/), enter the amount of ETH you wish to bridge, and click on the "Deposit" button.

<figure><img src="https://docs.swanchain.io/~gitbook/image?url=https%3A%2F%2F3478205236-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FcvUWH8GhRCqvKwuN0BGF%252Fuploads%252Fy2TXC9WGwWXhqcrLjBDj%252Fimage.png%3Falt%3Dmedia%26token%3De84ba6c1-5614-4f7e-9a8c-9deaf56f1968&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=feeb8fa6&#x26;sv=1" alt=""><figcaption></figcaption></figure>

**Step 3: Claiming Swan Credits**

1. Visit the [faucet page](https://faucet.swanchain.io/) and connect your wallet address.

<figure><img src="https://docs.swanchain.io/~gitbook/image?url=https%3A%2F%2Flh7-us.googleusercontent.com%2Fdocsz%2FAD_4nXfCUdtwVfvRsRfCyjt-OCtNzQk2PjbBKacqZ46Xgu0JhzearM7u_HkRWZcAs7YRQcK7m4avS_mlQDsnsuq1FKadeAuKuusBKZ3n_bcmPNk8e4lAA6m-kWy-o2eteamQd4TPcdZvAELsDqiBLu1e_yobUWY%3Fkey%3DPP4_jHREiRWUOtX6TLIS5g&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=b1863fa4&#x26;sv=1" alt=""><figcaption></figcaption></figure>

1. Click "Send Me Swan Credit Token" to claim Swan Credits. These credits can be used to pay Computing Providers when deploying an application in Lagrange.

{% hint style="info" %}
Each wallet can claim up to **25** tokens at a time. If your wallet balance exceeds **250** tokens, you won’t be able to claim any more tokens.
{% endhint %}


# Build and push your Docker image

This step will walk you through building and pushing your Docker image to your container registry. This is useful to building custom images for your use case.

1. Clone the [docker-application-template](https://github.com/swanchain/docker-application-template):

```
git clone https://github.com/swanchain/docker-application-template.git
```

2. Navigate to the root of the cloned repo:

```
cd docker-application-template
```

3. Build the Docker image (example: filswan/helloworld:v1.0):

```
docker build --platform linux/amd64 --tag <username>/<repo>:<tag> .
```

4. Push your container registry:

```
docker push <username>/<repo>:<tag>
```

> Note: After completing the above process, you can view the image information on the [docker hub](https://hub.docker.com/repository/docker/filswan/helloworld/general), as shown below:&#x20;

![img](https://github.com/user-attachments/assets/188d1415-747f-4c0e-a053-43ea587ea5fd)


# How to Use the Test Environment

The Lagrange testing environment is a testnet connected to the Swan Proxima Chain, designed for users and partners to try out features and transactions. To get started, visit <https://testnet.lagrange.computer>.

You'll need [SwanETH](#step-2-bridge-eth-from-sepolia-to-swan-proxima) for gas fees, which you can obtain by swapping [Sepolia ETH](#step-1-fund-your-wallet-with-sepolia-eth-tokens) via a [bridge](https://bridge.swanchain.io/). Additionally, you'll need [tSWAN ](#step3-claim-testswan)to pay Computing Providers for the resources required to power your Space (Application).&#x20;

Follow the steps outlined below to begin using the test environment.

### Network Info: Swan Testnet (Proxima) <a href="#proxima-testnet" id="proxima-testnet"></a>

| RPC URL            | [https://rpc-proxima.swanchain.io](https://rpc-proxima.swanchain.io/)                                                   |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------- |
| Chain ID           | 20241133                                                                                                                |
| Currency Symbol    | ETH                                                                                                                     |
| Block Explorer URL | <https://proxima-explorer.swanchain.io/>                                                                                |
| Chainlist          | <https://chainlist.org/chain/20241133>                                                                                  |
| Contract Addresses | Refer to the [Contract Addresses pages](https://docs.swanchain.io/network-reference/contract-addresses#proxima-testnet) |
| Connect Wallet     | Click [here](https://chainlist.org/chain/20241133) to connect your wallet to Swan Chain (Proxima) testnet               |

### 1.Set Up MetaMask

**Step 1: Add Swan Chain Proxima Testnet to MetaMask**

Swan, built at OP Stack, is currently available on the **Sepolia Testnet**. To engage with Swan, you'll need **Sepolia Testnet ETH**. Therefore, before adding Swan Testnet into MetaMask, it's essential to add the Sepolia Testnet to your wallet as well.

1\. Open MetaMask and click on the network name at the top ( "Ethereum Mainnet").

2\. Toggle **Show test networks** to reveal testnets.

<figure><img src="https://docs.swanchain.io/~gitbook/image?url=https%3A%2F%2F3478205236-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FcvUWH8GhRCqvKwuN0BGF%252Fuploads%252FkqLYn7Vk6jSnagGSGPJ2%252Fimage.png%3Falt%3Dmedia%26token%3Da916fc74-bd5a-4372-8947-7ba2cbc6e3b9&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=d0dcc6a3&#x26;sv=1" alt=""><figcaption></figcaption></figure>

3\. Scroll and select **Sepolia**

<figure><img src="https://docs.swanchain.io/~gitbook/image?url=https%3A%2F%2F3478205236-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FcvUWH8GhRCqvKwuN0BGF%252Fuploads%252FtxTaP9GEn8kvi5FjX19r%252Fimage.png%3Falt%3Dmedia%26token%3D8015bdbe-73a0-4220-ae7b-6f3172b48dbe&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=e55b9090&#x26;sv=1" alt=""><figcaption></figcaption></figure>

4.From the homepage of your wallet, click on the network selector in the top left, and then on **Add network** > **Add a network manually**.

<figure><img src="https://docs.swanchain.io/~gitbook/image?url=https%3A%2F%2F3478205236-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FcvUWH8GhRCqvKwuN0BGF%252Fuploads%252FKYDK3OOiU5izeJD6QjWL%252Fimage.png%3Falt%3Dmedia%26token%3Db4acf606-3dff-41c2-a644-da36c78d9612&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=fca6e079&#x26;sv=1" alt=""><figcaption></figcaption></figure>

5.Fill in details for Swan Chain Proxima Testnet:

| Network name       | Swan Proxima                                                          |
| ------------------ | --------------------------------------------------------------------- |
| New RPC URL        | [https://rpc-proxima.swanchain.io](https://rpc-proxima.swanchain.io/) |
| Chain ID           | 20241133                                                              |
| Currency symbol    | SwanETH                                                               |
| Block explorer URL | <https://proxima-explorer.swanchain.io/>                              |

If the above RPC fails, please try using this RPC: [https://rpc-proxima-tp.nebulablock.com](https://rpc-proxima-tp.nebulablock.com/)

6.Click **Save** or **Add** to save the network.

<figure><img src="https://docs.swanchain.io/~gitbook/image?url=https%3A%2F%2F3478205236-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FcvUWH8GhRCqvKwuN0BGF%252Fuploads%252Fy81dKvajvbf4yxZqvLUQ%252Fimage.png%3Falt%3Dmedia%26token%3D028defa0-946c-4d27-9f90-4339d4e7029a&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=e04467a6&#x26;sv=1" alt=""><figcaption></figcaption></figure>

### Step 2: Import Tokens: <a href="#step-2-import-tokens" id="step-2-import-tokens"></a>

1.Click on **Import tokens** at the bottom of the **Tokens** tab.

<figure><img src="https://docs.swanchain.io/~gitbook/image?url=https%3A%2F%2F3478205236-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FcvUWH8GhRCqvKwuN0BGF%252Fuploads%252FpIzwtIdodQ085ZPq3Mer%252Fimage.png%3Falt%3Dmedia%26token%3Dc8a3e360-82d0-4730-9a84-912196f9bed3&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=a301c7b4&#x26;sv=1" alt=""><figcaption></figcaption></figure>

2.Enter token contract addresses:

SWAN:

```
0x91B25A65b295F0405552A4bbB77879ab5e38166c
```

3.Token symbols and decimals should autofill; if not, check the block explorer.

4.Click **Import** to confirm.

## 2.Fund Your Wallet with Tokens

### Step 1: **Fund Your Wallet with SepoliaETH** <a href="#step-1-fund-your-wallet-with-sepolia-eth-tokens" id="step-1-fund-your-wallet-with-sepolia-eth-tokens"></a>

To engage in Swan Chain Proxima Testnet, you will require **SwanETH** tokens, which are bridged at a 1:1 ratio with **Sepolia ETH**. Therefore, it is necessary to obtain Sepolia Testnet ETH tokens initially from Alchemy and Quicknode faucets.

**Option 1: Mint Sepolia ETH on** [**PowFaucet**](https://sepolia-faucet.pk910.de/)

1.visit <https://sepolia-faucet.pk910.de/>

2\. Enter your address and click **Start Mining**

<figure><img src="https://docs.swanchain.io/~gitbook/image?url=https%3A%2F%2F3478205236-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FcvUWH8GhRCqvKwuN0BGF%252Fuploads%252FF7maNYjfxv0qyqDjaSnj%252Fimage.png%3Falt%3Dmedia%26token%3D4907393f-970b-44a5-8c7f-04a25d155192&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=dd215ccb&#x26;sv=1" alt=""><figcaption></figcaption></figure>

3\. Keep the process running continuously to accumulate more Sepolia ETH over time.

#### **Option 2: Claim Sepolia ETH on the Alchemy Sepolia Faucet:**

Alchemy allows registered users to claim up to 0.5 Sepolia ETH daily at the time of writing.

1\. To claim Sepolia ETH on Alchemy, Visit the[ faucet platform](https://sepoliafaucet.com/).

2\. Enter your wallet address and click “Send me ETH” to receive Sepolia ETH in your wallet.

<figure><img src="https://docs.swanchain.io/~gitbook/image?url=https%3A%2F%2F3478205236-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FcvUWH8GhRCqvKwuN0BGF%252Fuploads%252FX0N3fG8IPJl1agn2nEbX%252Fimage.png%3Falt%3Dmedia%26token%3D1df1d042-3333-403a-815a-d28d0e5d2cc5&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=4dc83963&#x26;sv=1" alt=""><figcaption></figcaption></figure>

**Option 3: Claim Sepolia ETH on the Quicknode Faucet:**

1.To claim Sepolia on Quicknode, visit the[ Quicknode Sepolia ETH faucet.](https://faucet.quicknode.com/ethereum/sepolia)

2.Connect your wallet to the platform. MetaMask, Trust Wallet, and other web3 wallets are supported on the network.

3\. Confirm your wallet and proceed to claim 0.05 SepoliaETH.

<figure><img src="https://docs.swanchain.io/~gitbook/image?url=https%3A%2F%2F3478205236-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FcvUWH8GhRCqvKwuN0BGF%252Fuploads%252F87cz8ZKoX5ok2UnInVir%252Fimage.png%3Falt%3Dmedia%26token%3D9fc48216-5999-4cad-9042-63996c23ae7c&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=e97f4c75&#x26;sv=1" alt=""><figcaption></figcaption></figure>

### Step 2: Bridge ETH from Sepolia to Swan Proxima <a href="#step-2-bridge-eth-from-sepolia-to-swan-proxima" id="step-2-bridge-eth-from-sepolia-to-swan-proxima"></a>

Go to the [Bridge](https://bridge.swanchain.io/) and select "**Swan Sepolia ETH**" in the top-left corner of the page to ensure you are bridging ETH from Sepolia to Swan Proxima Chain.&#x20;

Then, enter the amount of ETH you wish to bridge and click the "**Deposit**" button.

<figure><img src="/files/v5ZD47X8ma3SqxmeKPyd" alt=""><figcaption></figcaption></figure>

### Step3: Claim testSWAN

**Join the** [**Swan official Discord**](https://discord.com/invite/swanchain) and go to the **testnet-faucet** channel under the **LAGRANGE SPACE** section.

1. Type the command $swan\_faucet {your-wallet-address}.
2. Switch to the Swan Chain, import tokens into your wallet, and check your balance.

`Token contract address:`

`0x91B25A65b295F0405552A4bbB77879ab5e38166c`


# Space

This page is providing a way create a space for your code.

## What is Lagrange Space? <a href="#id-4067" id="id-4067"></a>

Spaces is a powerful yet user-friendly platform that enables users to build web applications with seamless access to the Lagrange ecosystem. It brings machine learning models to life through interactive applications, such as model exploration, visualization tools, and more.

## How Does Space Work? <a href="#id-7bd6" id="id-7bd6"></a>

Lagrange Spaces provides an infrastructure based on Streamlit, Gradio, and FastAPI, three popular frameworks for building web applications in Python. Users can write their code, and deploy their applications on the platform.&#x20;

Lagrange Spaces comes with a range of essential features, such as live reloading, and a custom domain option.

## Getting Started with Lagrange Spaces <a href="#aab8" id="aab8"></a>

1.[**Fund Your Wallet**](https://docs.swanchain.io/swan-chain/swan-chain-mainnet/swan-credit-token)**:**

Before you get started, fllowing [this guide](https://docs.swanchain.io/swan-chain/swan-chain-mainnet/swan-credit-token) to set up your MetaMask wallet, fund your wallet with ETH and Swan Credit Token (SwanC).

2.[**Create a New Space**](/spaces/create-space)**:**

Begin your Lagrange journey by creating a new Space.&#x20;

3.[**Build Your Space**](/spaces/build-space)**:**

Developing your code within your Space through the web interface

4.[**Fork a Space**](/spaces/fork-space)**:**

Discover how to duplicate and modify existing Lagrange Spaces.

5.[**Make Your Space Running**](/spaces/run-space)**:**

Understand the steps to make your Lagrange Space operational.


# Intro


# Lagrange Definition Language(LDL)

Customers/tenants define the deployment services, datacenters, and requirements, in a "manifest" file (deploy.yaml).&#x20;

The file is written in a declarative language called Lagrange Defintion Language(LDL).&#x20;

LDL is a human-friendly data standard for declaring deployment attributes. The LDL file is a "form" to request resources from the Network. LDL is compatible with the YAML standard and similar to Docker Compose files.&#x20;

Configuration files may end in `.yml` or `.yaml`.A complete deployment has the following sections:

* ​[version​](#version)
* [​services​](#services)
* ​[profiles​](#profiles)
* ​[deployment](#deployment)​

**Networking**

Networking - allowing connectivity to and between workloads - can be configured via the Lagrange Definition Language(LDL) file for a deployment. By default, workloads in a deployment group are isolated - nothing else is allowed to connect to them. This restriction can be relaxed.

### version <a href="#version" id="version"></a>

Indicates the version of the Lagrange configuration file. Currently only `"2.0"` one is accepted.

### services <a href="#services" id="services"></a>

The top-level `services` entry contains a map of workloads to be run on the Lagrange deployment. Each key is a service name; values are a map containing the following keys:

| Name         | Required | Meaning                                                                                                                                                       |
| ------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `image`      | Yes      | <p>Docker image of the container Best practices:</p><ul><li>avoid using <code>:latest</code> image tags as Computing Providers heavily cache images</li></ul> |
| `expose`     | Yes      | Entities allowed to connect to the services. See services.expose​                                                                                             |
| `depends-on` | No       | specifying dependencies for a particular service, indicates that the mentioned service relies on or requires certain other service to function properly       |
| `command`    | No       | Custom command use when executing container                                                                                                                   |
| `args`       | No       | Arguments to custom command use when executing the container                                                                                                  |
| `env`        | No       | Environment variables to set in running container. See services.env​                                                                                          |
| `ready`      | No       | ***NOTE - field is marked for future use and currently has no impact on deployments.***                                                                       |
| `model`      | No       | A configuration section that defines a list of models for the service                                                                                         |

#### services.depends-on <a href="#services.env" id="services.env"></a>

`depends-on` specifies dependencies for a particular service, indicates that the mentioned service relies on or requires certain other service to function properly

```
    depends-on:
       - db
```

#### services.env <a href="#services.env" id="services.env"></a>

A list of environment variables to expose to the running container.

```
env:
- "GF_PATHS_CONFIG=/opt/grafana/grafana.ini"
```

#### services.expose <a href="#services.expose" id="services.expose"></a>

**Notes Regarding Port Use in the Expose Stanza**

* HTTPS is possible in Lagrange deployments but only self-signed certs are generated.
* To implement signed certs the deployment must be front-ended via a solution such as Cloudflare.&#x20;
* You can expose any other port besides 80 as the ingress port (HTTP, HTTPS) port using as: 80 directive if the app understands HTTP / HTTPS. Example of exposing a React web app using this method:

```
    expose:
      - port: 3000 
        as: 80
```

* In the LDL it is only necessary to expose port 80 for web apps. With this specification, both ports 80 and 443 are exposed.

`expose` is a list describing what can connect to the service. Each entry is a map containing one or more of the following fields:

| Name     | Required | Meaning                                                      |
| -------- | -------- | ------------------------------------------------------------ |
| `port`   | Yes      | Container port to expose                                     |
| `as`     | No       | Port number to expose the container port as                  |
| `accept` | No       | List of hosts to accept connections for                      |
| `proto`  | No       | Protocol type (`tcp, udp, or http`)                          |
| `to`     | No       | List of entities allowed to connect. See services.expose.to​ |

The `as` value governs the default `proto` value as follows:

> ***NOTE*** - when as is not set, it will default to the value set by the port mandatory directive.

> ***NOTE*** - when one exposes as: 80 (HTTP), the Kubernetes ingress controler makes the application available over HTTPS as well, though with the default self-signed ingress certs.

| `port`     | `proto` default |
| ---------- | --------------- |
| 80         | http, https     |
| all others | tcp             |

#### services.expose.to <a href="#services.expose.to" id="services.expose.to"></a>

`expose.to` is a list of clients to accept connections from. Each item is a map with one or more of the following entries:

| Name      | Value                        | Default | Description                                               |
| --------- | ---------------------------- | ------- | --------------------------------------------------------- |
| `service` | A service in this deployment | ​       | Allow the given service to connect                        |
| `global`  | `true` or `false`            | `false` | If true, allow connections from outside of the datacenter |

If no service is given and `global` is true, any client can connect from anywhere (web servers typically want this).

If a service name is given and `global` is `false`, only the services in the current datacenter can connect. If a service name is given and `global` is `true`, services in other datacenters for this deployment can connect.

If `global` is `false` then a service name must be given.

#### service.model

`model` is a configuration section that defines a list of models for the service.Each model in the list has the following properties:

* **name**: This property specifies the name of the model.&#x20;
* **url**: This property specifies the URL from which the model's data can be downloaded.&#x20;
* **dir**: This property specifies the directory path within the container where the model's files will be stored after they are downloaded from the specified URL.

Example:

```
services:
  stable-diffusion-ui:
    image: sonic868/stable-diffusion:v1.0
    models:
      - name: illustroV3.safetensors
        url: https://civitai.com/api/download/models/151490
        dir: "/easy-diffusion/models/stable-diffusion"
```

### profiles <a href="#profiles" id="profiles"></a>

The `profiles` section contains named compute and placement profiles to be used in the deployment.

### deployment <a href="#deployment" id="deployment"></a>

The `deployment` section defines how to deploy the services. It is a mapping of service name to deployment configuration.

Each service to be deployed has an entry in the `deployment`. This entry is maps datacenter profiles to compute profiles to create a final desired configuration for the resources required for the service.

Example:

```
deployment:
  minesweeper:
    lagrange:
      count: 1
```

This says that the 20 instances of the `web` service should be deployed to a datacenter matching the `westcoast` datacenter profile. Each instance will have the resources defined in the `web` compute profile available to it.

**The final `deploy.yaml` should look like this:**

```
version: "2.0"

services:
  minesweeper:
    image: creepto/minesweeper
    expose:
      - port: 3000
        as: 80
    
deployment:
  minesweeper:
    lagrange:
      count: 1
```

Check out [here](https://lagrangedao.org/spaces/0x7E0c07e66CD480CDa94dEaaeEB5a84Fa9F8215e6/miner-bomb-bomb/files) to interact with the sample Space.

**Here is another sample `deploy.yaml`:**

```
version: "2.0"

services:
  db:
    image: postgres:11.6-alpine
    env:
      - POSTGRES_USER=codimd
      - POSTGRES_PASSWORD=rootadmin
      - POSTGRES_DB=codimd
    expose:
        - port: 5432
          as: 5432
          to:
            - service: db
    ready-cmd:
        - "psql"
        - "-w"
        - "-U"
        - "codimd"
        - "-d"
        - "codimd"
        - "-c"
        - "SELECT 1"
  codimd:
    image: hackmdio/hackmd:2.4.1
    env:
      - CMD_DB_URL=postgres://codimd:rootadmin@127.0.0.1:5432/codimd
      - CMD_USECDN=false
    depends-on:
      - db
    expose:
        - port: 3000
          as: 3000
          to:
            - global: true

deployment:
  db:
    lagrange:
      count: 1
  codimd:
    lagrange:
      count: 1
```

Check out [here](https://lagrangedao.org/spaces/0x7E0c07e66CD480CDa94dEaaeEB5a84Fa9F8215e6/CodiMD-Test/files) to interact with the sample Space.


# Lagrange-cli

Lagrange-cli is a distributed version control tool, which means that a local clone of the project is a complete version control space in IPFS.

### How to install

**Clone and Install `lagrange-cli`:** Clone the `lagrange-cli` repository and install it using pip:

```bash
git clone https://github.com/lagrangedao/lagrange-cli.git
cd lagrange-cli
pip install .
```

> **Note**: To clone and Install `lagrange-cli` on the [testnet](https://testnet.lagrangedao.org/), switch to the `new_testnet` branch:
>
> ```bash
> git clone https://github.com/lagrangedao/lagrange-cli.git
> git checkout origin/new_testnet -b new_testnet
> pip install .
> ```

### **How to use**

**1. Copy Space Link:** After creating your space on Lagrange, copy the link. It will look like this: `https://lagrangedao.org/<type>/<wallet_address>/<name>`.

**2. Clone Your Space:** Open your terminal and run the following command to clone your space repository:

```bash
lag clone <space_link>
```

Replace `<space_link>` with the link, you copied in Step 1.

**3. Navigate to Folder:** Change your directory to the folder created during the clone. Its name matches your space's name:

```bash
cd <space_name>
```

**4. Add Code Files:** Copy your code files and paste them into the folder (same as your space's name).

**5. Add and Commit Files:** Inside the cloned repository, add the code files you want to commit:

```bash
lag add file1 file2 file3 ...
```

To add all files in the current directory and subdirectories:

```bash
lag add .
```

Commit the added files with a descriptive message:

```bash
lag commit -m "commit message"
```

**6.Configure API Token:**&#x20;

You will be prompted to set your API token. Go to your Lagrange **Profile→Settings→Access Tokens**, and get your access token.

In your terminal, use the following command to set your API token:

```bash
lag config --api-token <your_access_token>
```

Replace `<your_access_token>` with the token you obtained in the previous step.

<figure><img src="/files/gNSZnuRdVInj179h2zMY" alt=""><figcaption></figcaption></figure>

**7. Push Changes to Space:** Push your committed changes to your own Space using:

```bash
lag push <space_link>
```


# Create Space

1\. Visit [https://lagrange.computer](https://lagrange.computer/) and connect your MetaMask

2\. Once logged in, click on the “Create new Space” button on the Space main page.

<figure><img src="/files/VGcpWyL5ENCXeeVdCY2q" alt=""><figcaption></figcaption></figure>

3\. Enter a name for your Space and select a License. Your Space’s URL will be automatically generated based on the name.

4\. Select the SDK you want to use for your Space (Docker, Streamlit, Static).

5\. Set your Space’s visibility to either public or private.

<figure><img src="/files/ODgxfG5ClbHFYS6XBdlW" alt=""><figcaption></figcaption></figure>


# Build Space

After creating a Space, you'll have an empty repository to develop your code. A `dockerfile` or `deploy.yaml` is required.

* A `dockerfile` is a text document that contains all the commands a user could call on the command line to assemble an image.&#x20;
* A `deploy.yaml` is a configuration file, written using [Lagrange Definition Language (LDL)](/spaces/intro/lagrange-definition-language-ldl)**,** which is used to specify deployment details for a Space on the Lagrange.

You can create/upload each file through the [**Web UI**](/spaces/build-space/option-2-web-interface) or via [**Lagrange-cli**](/spaces/intro/lagrange-cli).

### `dockerfile` or `deploy.yaml`

In determining the choice of deployment file, consider the following:

* Use a `dockerfile` if you don't have a pre-built image.
* Use `deploy.yaml` if you have an existing image to deploy.
* For many files, [**Lagrange-cli**](/spaces/intro/lagrange-cli) is recommended to choose to upload them.
* For large files( ＞50MB）, upload to [**Multichain.Storage**](https://www.multichain.storage/) first, and add its IPFS link to your `dockerfile` or `deploy.yaml`.


# Option 1: Langrange-cli

Lagrange-cli is a distributed version control tool, which means that a local clone of the project is a complete version control space in IPFS.

#### **How to use**

**1. Copy Space Link:** After creating your space on Lagrange, copy the link. It will look like this: `https://lagrange.computer/<type>/<wallet_address>/<name>`.

**2. Clone Your Space:** Open your terminal and run the following command to clone your space repository:

```bash
lag clone <space_link>
```

Replace `<space_link>` with the link, you copied in Step 1.

**3. Navigate to Folder:** Change your directory to the folder created during the clone. Its name matches your space's name:

```bash
cd <space_name>
```

**4. Add Code Files:** Copy your code files and paste them into the folder (same as your space's name).

**5. Add and Commit Files:** Inside the cloned repository, add the code files you want to commit:

```bash
lag add file1 file2 file3 ...
```

To add all files in the current directory and subdirectories:

```bash
lag add .
```

Commit the added files with a descriptive message:

```bash
lag commit -m "commit message"
```

**6.Configure API Token:**&#x20;

You will be prompted to set your API token. Go to your [**Lagrange**](https://lagrangedao.org/main) **Profile→Settings→Access Tokens**, and get your access token.

In your terminal, use the following command to set your API token:

```bash
lag config --api-token <your_access_token>
```

Replace `<your_access_token>` with the token you obtained in the previous step.

<figure><img src="/files/gNSZnuRdVInj179h2zMY" alt=""><figcaption></figcaption></figure>

**7. Push Changes to Space:** Push your committed changes to your Space using:

```bash
lag push <space_link>
```


# Option 2: Web Interface

You have the choice to create a new file or upload your existing files through the web interface.

### Create a New File

1\. Start by selecting the **Files and version** tab, and then clicking **Contribute** → **Create a new file.**

<figure><img src="/files/5vOIaqVbRL9F3Cx6WXLe" alt=""><figcaption></figcaption></figure>

2\. And then you can choose a name for your file, add content, and save your file by clicking on "Commit new file".

<figure><img src="/files/mxmDJlcGbdpEkngBEoRq" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
When deploying a Space, provide either a **`dockerfile`** or **`deploy.yaml`**, or both. If both are provided, **`deploy.yaml`** takes precedence and will be executed while the **`dockerfile`**&#x77;ill be ignored.
{% endhint %}

### Upload Files

1.Start by selecting the **Files and version** tab, and then clicking **Contribute** → **Upload files.**

<figure><img src="/files/GYOLtoEb2gknhh2H17Up" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/Xhui38nhaNzStvSmugvn" alt=""><figcaption></figcaption></figure>

Note that, if you prefer, you can also utilize [**Lagrange-cli**](/spaces/intro/lagrange-cli) to upload code files to your Space


# Fork Space

Forking a Space can be useful if you want to build a new demo using another demo as an initial template. Forked Spaces can also be useful if you want to have an individual Upgraded Space for your use with fast inference.

1. To fork a Space, visit [https://lagrange.computer](https://lagrange.computer/) and simply click on "Fork."

<figure><img src="https://lh4.googleusercontent.com/Lqdr7r5ZmEoqP3IeI2efoWMuB_TjZ0bdnxdpCNVCwM5FPgvMaSYOP9SLZgEczYi_JVsJocrcvdjMDH5radJcmH8TUld6FSp6pEkUsgyJdzhjmmCPeQliTDdWNrV-FgL3XToZdrVT0y9T7L2VpzXc8EE" alt=""><figcaption></figcaption></figure>

2. Once forked, you have the option to rename your Space.

<figure><img src="https://lh6.googleusercontent.com/UgRnSc6Lk5gSLwqprHsApqfQL6mrU1pEX1ac58JQz6do3zKa0yoT3_xeKRTaMRK005KRM2oKzuCt6uV9rGeNi2nfLBBvhw8jWg-0A_Vz_ukA_1v4XJgIQpGiVchyZdRh-vRFavhjyOayd0VUvafzyQU" alt=""><figcaption></figcaption></figure>


# Run Space

1\. Click on **\[Settings]** and select your preferred hardware, and proceed with the payment.

<figure><img src="https://lh4.googleusercontent.com/QrdX0E4o4arOYk9XEyLfDdT5r-MVa-bqMOGOJ7i7Ay7OGKNt_z4cSPSGue063EJItX2IQmMjVBv8FQskG2eqfPFeOuvFBdtj45BvAoecY6W3Kiu1Lv8AwBehcxj4IXQmNvC1U6ZPxIgFJNhQeFa5wTc" alt=""><figcaption></figcaption></figure>

For additional info about hardware, refer to the[Space Hardware](/spaces/space-settings/space-hardware)

<figure><img src="https://lh3.googleusercontent.com/ur12FW4N4N9oFzS5J5nO55B5wZMb9wHtVV6kvkC5oHumsfut9B9cDmDvSlabaezsQ9HN_7ebG9s4wwAlOHsRmB-X2laTri9PAf5228lLlCAOAexnb_LE_UXW6MXfyhryuSlZbNApJwtjwxXiU1LoKOI" alt=""><figcaption></figcaption></figure>

2\. After payment confirmation, observe the status tag of your Space. It will transition from "**Waiting for Transaction**" to "**Deploying**," and finally to "**Running**".

<figure><img src="https://lh3.googleusercontent.com/GynEwa-x3Vg008tyW70OlJ11Du-WbouUPAfRhH1WKODaXMIxS6-8RsrVoXxRxgRkQMrPORtnnIkRL2W2usMpMVZNb8V6b5KMeesy_TYVsJm4lu4ikYwThdw4kie1uZWER_6VMdsxdIO5E7aCLchRTmE" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
**Note: There are six types of Space statuses, as follows:**

* **Created**: The Space has been successfully created.
* **Waiting For Transaction**: Awaiting payment confirmation.
* **Assigning To Provider**: Matching the Space with a computing provider.
* **Deploying**: The Space is currently being deployed to the provider.
* **Running**: The Space has been successfully deployed.
* **Failed**: The deployment has encountered an error.
* **Stopped**: The deployment has ceased before its scheduled expiration due to unforeseen reasons.
* **Expired**: The deployment has concluded upon reaching its expiration date.
  {% endhint %}

With your App going live, you can now interact with it.


# Space Settings


# Instance Type

### Instance Type Naming Convention <a href="#instance-type-names" id="instance-type-names"></a>

Instance types are named based on their family, generation, processor family, additional capabilities, and size.

* The first position of the instance type name indicates the instance family, for example `p`.&#x20;
* The second position indicates the instance generation, for example `1`.&#x20;
* The third position indicates the processor family, for example `a`.&#x20;
* The remaining letters before the period indicate additional capabilities, such as instance store volumes.&#x20;
* After the period (`.`) is the instance size, such as `small` or `4xlarge`.

<figure><img src="/files/Gr8zBi9QnJoy3owWB0oL" alt="" width="375"><figcaption></figcaption></figure>

#### **Instance families**

* **C** – Compute optimized
* **D** – Dense storage
* **F** – FPGA
* **G** – Graphics intensive
* **Hpc** – High performance computing
* **I** – Storage optimized
* **M** – General purpose
* **Mac** – macOS
* **P** – GPU accelerated
* **R** – Memory optimized
* **T** – Burstable performance
* **U** – High memory
* **VT** – Video transcoding
* **X** – Memory intensive

#### **Processor families**

* **a** – AMD processors
* **i** – Intel processors

#### **Additional capabilities**

* **d** – instance store volumes
* **e** – Extra storage or memory
* **z** – High performance
* **flex** – Flex instance


# Space Hardware

Lagrange offers a diverse range of hardware resources, allowing you to select the configuration that perfectly aligns with your needs.

You can start with the free one, which includes 16 GiB Memory, 2 vCPU cores, and 60 GB of non-persistent disk space. Alternatively, you have the option to upgrade to more powerful hardware, including various GPU accelerators and persistent storage, all available at highly competitive prices.&#x20;

Please refer to the table below for detailed specifications and pricing:

<table><thead><tr><th width="172">Instance Type</th><th width="141">GPU</th><th width="81">vCPU</th><th width="131">Memory/GiB</th><th width="106">Disk/GiB</th><th width="115">SWAN per hour</th></tr></thead><tbody><tr><td>C1ae.small</td><td>CPU only </td><td>2</td><td>2</td><td>5</td><td>2</td></tr><tr><td>C1ae.medium</td><td>CPU only </td><td>4</td><td>4</td><td>5</td><td>2.5</td></tr><tr><td>G2ae.small</td><td>Nvidia T4 </td><td>4</td><td>8</td><td>20</td><td>2.5</td></tr><tr><td>Hpc2ad.xlarge</td><td>Nvidia A2000 </td><td>4</td><td>8</td><td>20</td><td>2.5</td></tr><tr><td>R2ae.2xlarge</td><td>Nvidia T4 </td><td>8</td><td>32</td><td>20</td><td>2.5</td></tr><tr><td>G2ae.medium</td><td>Nvidia T4 </td><td>8</td><td>16</td><td>20</td><td>2.6</td></tr><tr><td>Hpc2az.xlarge</td><td>Nvidia A2000 </td><td>8</td><td>16</td><td>20</td><td>2.6</td></tr><tr><td>T1az.large</td><td>Nvidia T4 </td><td>8</td><td>64</td><td>20</td><td>2.6</td></tr><tr><td>T2az.large</td><td>Nvidia T4 </td><td>12</td><td>128</td><td>20</td><td>2.7</td></tr><tr><td>M1ae.small</td><td>Nvidia 2060 </td><td>4</td><td>8</td><td>20</td><td>3</td></tr><tr><td>M2ae.xlarge</td><td>Nvidia 3070 Ti</td><td>8</td><td>16</td><td>20</td><td>3</td></tr><tr><td>M1ae.medium</td><td>Nvidia 2060 </td><td>4</td><td>16</td><td>20</td><td>3.1</td></tr><tr><td>M1ae.large</td><td>Nvidia 3060 </td><td>8</td><td>8</td><td>20</td><td>3.1</td></tr><tr><td>T1ae.2xlarge</td><td>Nvidia 3070 Ti</td><td>12</td><td>64</td><td>20</td><td>3.1</td></tr><tr><td>T1ae.small</td><td>Nvidia 2060 </td><td>12</td><td>64</td><td>20</td><td>3.2</td></tr><tr><td>M1ae.xlarge</td><td>Nvidia 3070 </td><td>8</td><td>8</td><td>20</td><td>4</td></tr><tr><td>M2ae.small</td><td>Nvidia 3060 Ti</td><td>4</td><td>8</td><td>20</td><td>4</td></tr><tr><td>M2ae.large</td><td>Nvidia 3070 </td><td>4</td><td>8</td><td>20</td><td>4</td></tr><tr><td>M2ae.medium</td><td>Nvidia 3060 Ti</td><td>8</td><td>16</td><td>20</td><td>4.1</td></tr><tr><td>T1ae.xlarge</td><td>Nvidia 3070 </td><td>12</td><td>64</td><td>20</td><td>4.1</td></tr><tr><td>T1ae.large</td><td>Nvidia 3060 Ti</td><td>12</td><td>64</td><td>20</td><td>4.2</td></tr><tr><td>M1ae.2xlarge</td><td>Nvidia 2080 Ti</td><td>4</td><td>8</td><td>20</td><td>4.5</td></tr><tr><td>M1ae.3xlarge</td><td>Nvidia 2080 Ti</td><td>8</td><td>16</td><td>20</td><td>4.6</td></tr><tr><td>R1ae.small</td><td>Nvidia 2080 TI</td><td>8</td><td>32</td><td>20</td><td>4.7</td></tr><tr><td>G1ae.small</td><td>Nvidia 3080 </td><td>4</td><td>8</td><td>20</td><td>5</td></tr><tr><td>G1ae.medium</td><td>Nvidia 3080 </td><td>8</td><td>16</td><td>20</td><td>5.5</td></tr><tr><td>R1ae.medium</td><td>Nvidia 3080 </td><td>8</td><td>32</td><td>20</td><td>5.5</td></tr><tr><td>Hpc2ad.small</td><td>Nvidia 4060 Ti</td><td>4</td><td>8</td><td>20</td><td>6</td></tr><tr><td>Hpc2az.small</td><td>Nvidia 4060 Ti</td><td>8</td><td>16</td><td>20</td><td>6.1</td></tr><tr><td>Hpc2ad.medium</td><td>Nvidia 4070 </td><td>4</td><td>8</td><td>20</td><td>8</td></tr><tr><td>Hpc2az.medium</td><td>Nvidia 4070 </td><td>8</td><td>16</td><td>20</td><td>8.1</td></tr><tr><td>R2ae.small</td><td>Nvidia 4070 </td><td>8</td><td>32</td><td>20</td><td>8.2</td></tr><tr><td>G1ae.large</td><td>Nvidia 3080 Ti</td><td>4</td><td>8</td><td>20</td><td>9</td></tr><tr><td>G1ae.xlarge</td><td>Nvidia 3080 Ti</td><td>8</td><td>16</td><td>20</td><td>9.1</td></tr><tr><td>Hpc1ae.small</td><td>Nvidia 3090 </td><td>4</td><td>8</td><td>20</td><td>9.1</td></tr><tr><td>Hpc1ae.medium</td><td>Nvidia 3090 </td><td>8</td><td>16</td><td>20</td><td>9.2</td></tr><tr><td>T1ae.medium</td><td>Nvidia 2080 Ti</td><td>12</td><td>64</td><td>20</td><td>9.2</td></tr><tr><td>T1ae.3xlarge</td><td>Nvidia 3080 Ti</td><td>12</td><td>64</td><td>20</td><td>9.2</td></tr><tr><td>R1ae.large</td><td>Nvidia 3090 </td><td>8</td><td>32</td><td>20</td><td>9.25</td></tr><tr><td>Hpc1ae.large</td><td>Nvidia 3090 Ti</td><td>4</td><td>8</td><td>20</td><td>10.5</td></tr><tr><td>Hpc1ae.xlarge</td><td>Nvidia 3090 Ti</td><td>8</td><td>16</td><td>20</td><td>11</td></tr><tr><td>Hpc2ad.large</td><td>Nvidia 4080 </td><td>4</td><td>8</td><td>20</td><td>12</td></tr><tr><td>Hpc2ad.1xlarge</td><td>Nvidia A5000 </td><td>4</td><td>8</td><td>20</td><td>12</td></tr><tr><td>Hpc2az.large</td><td>Nvidia 4080 </td><td>8</td><td>16</td><td>20</td><td>12.1</td></tr><tr><td>Hpc2az.1xlarge</td><td>Nvidia A5000 </td><td>8</td><td>16</td><td>20</td><td>12.1</td></tr><tr><td>R2ae.medium</td><td>Nvidia 4080 </td><td>8</td><td>32</td><td>20</td><td>12.1</td></tr><tr><td>R2ae.1xlarge</td><td>Nvidia A5000 </td><td>8</td><td>32</td><td>20</td><td>12.1</td></tr><tr><td>Hpc2ae.small</td><td>Nvidia 4090 </td><td>4</td><td>8</td><td>20</td><td>14.5</td></tr><tr><td>Hpc2ae.large</td><td>Nvidia 4090 Ti</td><td>4</td><td>8</td><td>20</td><td>14.5</td></tr><tr><td>Hpc2ae.medium</td><td>Nvidia 4090 </td><td>8</td><td>16</td><td>20</td><td>14.6</td></tr><tr><td>Hpc2ae.xlarge</td><td>Nvidia 4090 Ti</td><td>8</td><td>16</td><td>20</td><td>14.65</td></tr><tr><td>R2ae.large</td><td>Nvidia 4090 </td><td>8</td><td>32</td><td>20</td><td>14.7</td></tr><tr><td>T1az.2xlarge</td><td>Nvidia 4090 </td><td>8</td><td>64</td><td>20</td><td>14.75</td></tr><tr><td>T1az.3xlarge</td><td>Nvidia 4090 Ti</td><td>8</td><td>64</td><td>20</td><td>14.75</td></tr><tr><td>T2az.2xlarge</td><td>Nvidia 4090 </td><td>12</td><td>128</td><td>20</td><td>14.8</td></tr><tr><td>T2az.3xlarge</td><td>Nvidia 4090 Ti</td><td>12</td><td>128</td><td>20</td><td>14.8</td></tr><tr><td>Hpc1ae.2xlarge</td><td>NVIDIA A4000 </td><td>4</td><td>8</td><td>20</td><td>18.5</td></tr><tr><td>Hpc1ae.3xlarge</td><td>NVIDIA A4000 </td><td>8</td><td>16</td><td>20</td><td>18.6</td></tr><tr><td>R2ae.xlarge</td><td>Nvidia A4000 </td><td>8</td><td>32</td><td>20</td><td>18.7</td></tr><tr><td>T1az.4xlarge</td><td>Nvidia A4000 </td><td>8</td><td>64</td><td>20</td><td>18.8</td></tr><tr><td>T2az.4xlarge</td><td>Nvidia A4000 </td><td>12</td><td>128</td><td>20</td><td>18.9</td></tr><tr><td>T1az.5xlarge</td><td>Nvidia A6000 </td><td>8</td><td>64</td><td>20</td><td>25.5</td></tr><tr><td>T2az.5xlarge</td><td>Nvidia A6000 </td><td>12</td><td>128</td><td>20</td><td>25.6</td></tr><tr><td>T1az.6xlarge</td><td>Nvidia L40 </td><td>8</td><td>64</td><td>20</td><td>35</td></tr><tr><td>T2az.6xlarge</td><td>Nvidia L40 </td><td>12</td><td>128</td><td>20</td><td>35.5</td></tr><tr><td>T1az.7xlarge</td><td>Nvidia L40s </td><td>8</td><td>64</td><td>20</td><td>36</td></tr><tr><td>T2az.7xlarge</td><td>Nvidia L40s </td><td>12</td><td>128</td><td>20</td><td>37</td></tr><tr><td>G2ae.large</td><td>Nvidia A10G </td><td>4</td><td>8</td><td>20</td><td>40</td></tr><tr><td>G2ae.lxarge</td><td>Nvidia A10G </td><td>12</td><td>16</td><td>20</td><td>41</td></tr><tr><td>R2ae.3xlarge</td><td>Nvidia A10G </td><td>8</td><td>32</td><td>20</td><td>41</td></tr><tr><td>T1az.xlarge</td><td>Nvidia A10G </td><td>8</td><td>64</td><td>20</td><td>42</td></tr><tr><td>T2az.xlarge</td><td>Nvidia A10G </td><td>12</td><td>128</td><td>20</td><td>43</td></tr><tr><td>P1ae.small</td><td>Nvidia A100 </td><td>8</td><td>32</td><td>20</td><td>60</td></tr><tr><td>P1ae.medium</td><td>Nvidia A100 </td><td>12</td><td>64</td><td>20</td><td>61</td></tr><tr><td>T1az.9xlarge</td><td>Nvidia H200 </td><td>8</td><td>64</td><td>20</td><td>100</td></tr><tr><td>T2az.9xlarge</td><td>Nvidia H200 </td><td>12</td><td>128</td><td>20</td><td>101</td></tr><tr><td>P1ae.large</td><td>Nvidia H100 </td><td>8</td><td>32</td><td>20</td><td>140</td></tr><tr><td>P1ae.xlarge</td><td>Nvidia H100 </td><td>12</td><td>64</td><td>20</td><td>141</td></tr><tr><td>T1az.8xlarge</td><td>Nvidia H100 </td><td>8</td><td>64</td><td>20</td><td>141</td></tr><tr><td>T2az.8xlarge</td><td>Nvidia H100 </td><td>12</td><td>128</td><td>20</td><td>142</td></tr><tr><td>T1az.10xlarge</td><td>Nvidia H800 </td><td>8</td><td>64</td><td>20</td><td>195</td></tr><tr><td>T2az.10xlarge</td><td>Nvidia H800 </td><td>12</td><td>128</td><td>20</td><td>196</td></tr></tbody></table>

*Note: The table above represents the currently available hardware options. Stay tuned for more exciting updates as we expand our offerings with additional hardware resources in the future.*


# Use  Case

Lagrange offers a diverse ecosystem of spaces across four several categories. Explore our curated selection to enhance your workflow, unleash creativity, enjoy classic games, and dive into blockchain technology.

### AI Agent

Explore the capabilities of AI agents using Lagrange technology for advanced machine learning applications

* [**Eliza-SwanChain**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Eliza-swanchain/app)**:** An AI agent using Eliza framework that can answer all questions related to Swan Chain

### **AI and Creative Spaces**

Harness cutting-edge AI models to generate content and boost your creative projects.

* [**MusicGen**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/MusicGen/app): Create original music tracks using simple text prompts.
* [**Stable Diffusion**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Stable-Diffusion-Base-LoRA/app): Transform text descriptions into stunning AI-generated images.
* [**Text-to-Speech**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Text-to-Speech/app): Convert written text into natural-sounding speech effortlessly.
* [**ComfyUI**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/ComfyUI/app): Streamline AI image generation with an intuitive graphical interface.
* [**Llama3-8B-LLM-Chat**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Llama3-8B-LLM-Chat/app)**:** Meta’s Llama 3, the next iteration of the open-access Llama family.

### **Gaming Spaces**&#x20;

Relive classic gaming experiences and challenge yourself with timeless favorites.

* [**Tetris**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/tetris/app): Test your spatial skills with this iconic block-stacking puzzle.
* [**Super Mario**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Mario/app): Embark on a nostalgic adventure with gaming's most famous plumber.
* [**Pac-Man**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/pac-man/app): Navigate mazes and outmaneuver ghosts in this beloved arcade classic.
* [**2048**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/2048/app): Slide numbered tiles and aim for the elusive 2048 in this addictive challenge.

### **Blockchain Spaces**&#x20;

Explore and interact with decentralized technologies using these powerful tools.

* [**Chainnode-RPC**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/chainnode-rpc/app): Access and analyze blockchain data with this comprehensive RPC interface.
* [**Uniswap**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/uniswap/app): Experience decentralized trading on the Ethereum blockchain.

### **Development Tools**&#x20;

Enhance your coding workflow with these essential development utilities.

* [**Terminal**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Terminal/app): Access a versatile command-line interface directly in your browser.
* [**JSON-View**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Json-view/app): Visualize and interact with JSON data in a user-friendly web environment.
* [**Jupyter**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Jupyter-Labs/app): Develop, document, and execute code in an interactive notebook interface.

***

### Contribute to Lagrange

Have an idea for a new space? We welcome contributions from our community!

* [Fork and build your first Space](https://docs.lagrangedao.org/spaces/fork-space)
* [Explore our model repository](https://github.com/swanchain/awesome-swanchain)

Join us in expanding the Lagrange ecosystem and share your innovations with developers worldwide.


# Datasets


# Data Card

A datacard serves as a detailed overview and documentation for a dataset. Creating a `readme.md` file in the dataset's root directory is a good practice to provide necessary information about the dataset to users. You can use the sample datacard as a template and customize it based on your dataset's specific details.

Here's a sample [datacard](https://github.com/lagrangedao/datasets) structure for a `readme.md` file:

## Dataset Title

### Table of Contents

* Description
* Content
* Usage
* Licenses and Attribution
* Citation
* Contact

### Description

A brief description of the dataset, its purpose, and the problem it aims to address.

### Content

* A detailed explanation of the dataset's content, including:
  * Data sources
  * Features/variables/columns and their descriptions
  * Data format (CSV, JSON, etc.)
  * Size of the dataset
  * Temporal and spatial coverage (if applicable)

### Usage

* Potential use cases of the dataset
* Any preprocessing steps or data cleaning performed
* Any known limitations or biases in the dataset
* Guidelines for using the dataset responsibly and ethically

### Licenses and Attribution

* Information about the dataset's license
* Required attributions or acknowledgments
* Any third-party content, data, or code used in the dataset

### Citation

Provide a suggested citation format for users who reference the dataset in their research or work.

### Contact

* Contact information for the dataset's creators or maintainers
* Any relevant links, such as the project website, related publications, or social media profiles

When you create the `readme.md` file with this structure, it will serve as the datacard for your dataset, providing users with all the necessary information they need to understand and utilize the dataset effectively.


# Models


# Case Study


# Stable Diffusion

####


# How to Build Stable Diffusion Space

This tutorial guides you on how to fork and run a Stable Diffusion Space.

#### How to Fork the Base Space and Rename it:

1\. Visit \[[https://lagrange.computer/spaces\]](https://lagrange.computer/spaces) and log in to your account

2\. Visit the [Stable Diffusion Base Space](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Stable-Diffusion-Base-LoRA/app), and click on the \[Fork] button to create a duplicate of the Base Space.

<figure><img src="https://lh4.googleusercontent.com/UJnbM8oLVJXDjWZZkxQ7fDCek29pVJVBGxoAmvMUyhRzzX-z_WtvKNWKwzYH3xxQZjlwI9UV5Tl3hV_DjFsf6h9zRaxy6EACBGTbtvwDK2P47l8KcTDISitGLMZUdY2gy3Q7NtKejlP3Hdzhoy9xm-M" alt=""><figcaption></figcaption></figure>

<figure><img src="https://lh6.googleusercontent.com/oRy_T_MNTSJ6bqGTJtiHK_Pw-tzBLhY3r6e1UFzPxxxxD1bh5OImd22rOktVH0Cs1iO-CW1B1-a6J8JYn0GvSy_sZn1PWvuIpNg5yHGTpTI3pgWzxh9Zrm4q2eL-iyW2AAYlgOA29FZR1LN4CGw9t3c" alt=""><figcaption></figcaption></figure>

3\. You can either click on the \[Just Fork, choose config later] or select your preferred hardware, and proceed with the payment.

It's recommended to choose "config later" if you anticipate adding more models to your Space in the future to avoid unnecessary redeployments.

<figure><img src="https://lh5.googleusercontent.com/S2daQ_7aiKXdAxCogyBDELByzC282gzCATDRIa9vhx_0xYT8nrqYhAvu5kAvbrE5s-O1kYqzZ1jZYG9pnFYxqK8k-FfD1KFuAMh5g9GJ1GjbYtP5NxueHVCP3QUA3DO25DqUo-jSA63e6hPaJjKizzU" alt=""><figcaption></figcaption></figure>

In your forked Space, you can click the **\[Settings]** button and scroll down to the Rename section to rename your Space.

***Note:** Please note that after you change the Space name, the Space link will also be updated. Make sure to share the new link with others as needed.*

<figure><img src="https://lh4.googleusercontent.com/cdSKmw-kdgN5Zlm2mQ05GiCantlI8hbbfc1Ahc5cp6DcU6Fw4dMlftmYWJCskoq6tAl7oB5sXuUm549WhQ9EcIHxt6RLVcnTVwt-228mqOKEZ5KDiXmZintlNr3CeUKLzw5lTksOslWfjwwRFE7Mb1U" alt=""><figcaption></figcaption></figure>

#### How to Add More Models

If you prefer to utilize the default LoRA models provided by Base Space, you can proceed directly to the section on How to Get Your Space Running.

However, if the available models do not precisely align with your image preferences, you have the option to enhance your Stable Diffusion Space by adding more models by following the below steps.

1\. Find models you liked from[ Civitai](https://civitai.com/?query=lora) and[ Hugging Face](https://huggingface.co/models?search=lora), and get the downloading link of the model.

2\. Go to \[Files and versions] and Update the Dockerfile, you need to replace the \<model\_download\_link> and \<your\_model\_name>, then add the below command to the Dockerfile:

\# Command example:

```
RUN wget <model_download_link> -O /stable-diffusion-webui/models/Lora/<your_model_name>
```

<figure><img src="https://lh6.googleusercontent.com/JaUXPWNgWgo640KbJou5RLRtsUjc2X0LDdDZ-azOUxHzKFD2p25gLtUORnh_fxBiNvK9x3ovlkkD5vyfbDdaAN0yY2_uAxyDu6WZMnev5l7zk0XPR2mDly5qye32xdoAyvPOWHREK1IDqyH4AL-sQ84" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/RSgrtbhjSL3YxCJWfuyK" alt=""><figcaption></figcaption></figure>

#### How to Get Your Space Running

To set up your Stable Diffusion Space for generating images from textual descriptions, you must

1. deploy the Stable Diffusion Web UI, a user-friendly interface that facilitates interaction with the model. Additionally,
2. installing LoRA extensions enhances the Web UI's capabilities, enabling support for LoRA models.
3. installing the actual LoRA models to enable image generation.

#### **Step1: Deploy the Stable Diffusion web UI (Automatic 111)**

1\. Click on \[Settings] and select your preferred hardware meeting the below requirements:

* At least one GPU
* At least 8 vCPUs
* Minimum 50GB SSD storage
* Minimum 32GB memory
* Minimum 50MB bandwidth
* Here are the GPUs we recommend:
  * T4, RTX 4090, 3090Ti, 3090, 3080Ti, 3080, 3060Ti, 2060, 2070, 2080, 2080Ti, A100, H100

**Ensure you choose hardware with at least one GPU**; without it, Stable Diffusion Space won't function.

And proceed with the payment.

<figure><img src="/files/efXtT0biC9nJCptYdztQ" alt=""><figcaption></figcaption></figure>

<figure><img src="https://lh3.googleusercontent.com/ur12FW4N4N9oFzS5J5nO55B5wZMb9wHtVV6kvkC5oHumsfut9B9cDmDvSlabaezsQ9HN_7ebG9s4wwAlOHsRmB-X2laTri9PAf5228lLlCAOAexnb_LE_UXW6MXfyhryuSlZbNApJwtjwxXiU1LoKOI" alt=""><figcaption></figcaption></figure>

2\. After payment confirmation, observe the status tag of your Space. It will transition from "Waiting for Transaction" to "Deploying," and finally to "Running" once the Stable Diffusion web UI is successfully deployed on your Space.

<figure><img src="https://lh3.googleusercontent.com/GynEwa-x3Vg008tyW70OlJ11Du-WbouUPAfRhH1WKODaXMIxS6-8RsrVoXxRxgRkQMrPORtnnIkRL2W2usMpMVZNb8V6b5KMeesy_TYVsJm4lu4ikYwThdw4kie1uZWER_6VMdsxdIO5E7aCLchRTmE" alt=""><figcaption></figcaption></figure>

After a few minutes, you can access the Stable Diffusion web UI in the \[**App**] tab of your Space.

*\*Note: Do not panic if you encounter a "404" or "502" error while accessing the web UI. These errors indicate that the web UI is currently deploying, and the process typically takes around 1-10 minutes to complete.*

#### **Step 2: Install a LoRA Model Into Automatic1111**

Before using LoRA models in your Stable Diffusion Web UI, you need to install the LoRA extension.

1\. Click on the \[**App**] tab to Launch the Stable Diffusion Web UI in the space.

<figure><img src="https://lh3.googleusercontent.com/bv9DMnddVoAL2FaT_iw1_Izp87oy4GbpG5hjnFuICcjm62YrmND_WqicTYocsGmS-hYeht1j6d0FjhE0x_qD3su3OOsGJz8rnlkgj3F8xoOBqEbox-mEhv4upEzaQkU2RlnTTkKzPkZ5Yxw4hxI6FHU" alt=""><figcaption></figcaption></figure>

2\. Open the \[**Extensions**] tab, click on \[**Install from URL**], and copy the following link:

`https://github.com/kohya-ss/sd-webui-additional-networks.git`

And Click the **"Install"** button.

<figure><img src="https://lh6.googleusercontent.com/8KNP0TXzh5EBUFjrAVPmClMgxMG1VDEI_MzoY36EBuhY5jD4KzDmChiq9QVVn8slZZxc2LfmoHcw6s0Akij5KuJvL9Y2HZ7ZgtRO-M4_x5rVaH6Vzc6dUHImD7ys7lGrkUu2gIU6t-cy66LuJwp-Mv4" alt=""><figcaption></figcaption></figure>

3\. To verify if the installation was successful, switch to the **\[Installed]** tab. and Click on the **\[Apply and restart UI]** button.

<figure><img src="https://lh3.googleusercontent.com/D34PMjWXZjDEz9mtIKJCLu6vkoUgJGsHN7Fh0FdUA30vQAIaCbI8_Q-sYh1E3qjkZRJsLjBBDo16S9diY8TMUIr_GfcBRcdOa89jTiBS0W7m9eSCX5_Zvub8Q_tnQLdiAZBQG7C7uWLq_W3GROkmFpo" alt=""><figcaption></figcaption></figure>

4\. Open the **\[Settings]** tab and switch to the **\[Additional Networks]** tab, paste stable-diffusion-webui/models/Lora in the input field of \[**Extra paths to scan for LoRA models]** and then click **\[Apply settings]**.

<figure><img src="https://lh4.googleusercontent.com/ABPxubNgvGpLUgdYM0DHN3ub-h34hu0g8hLt0rdQmsujA6oDtTjt64zVPq-uVMrYGUiD6EzLcBbWV-4xgPz8CUdRNVgPowpzD87tn_NvTshfZQZZJ90q50R2bQx1FyKe2r5Kpq4MeFb5AKHjRVXc_O0" alt=""><figcaption></figcaption></figure>

<figure><img src="https://lh4.googleusercontent.com/5dVz0nAVDWgvQ7qOrPWSycUBAifZQyiyFV9fb6vV5rWrE-iNYoaLsSYx4zZIqQYTQLjzGh06yftmn_SDJujpTEUuRlaZYXFoqSOuZlqRd0-gYe-OsMg0Z6O7hpB_nHKvQWAjY0BqU8PV6Qim2Km34PI" alt=""><figcaption></figcaption></figure>

#### **Step 3: Set Up LoRA Models**

Although the LoRA Extension has been installed successfully, it's not enough to start generating images. You need to install your actual LoRA Models to the specified folder as well.

1\. Click the **\[App]** tab in your Space to access the launched Stable Diffusion Web UI.

2\. Choose your desired checkpoint model from the preloaded options (e.g., "chilloutmix-Ni.safetensors" or "V1-5-pruned-emaononly.safetensors").

3\. Click on the **\[txt2img]** tab and select the icon of "Additional Networks" under the "Generate" button, then choose **\[LoRA]**.

<figure><img src="https://lh4.googleusercontent.com/Tj_whyH8mY6b6-7zJOtw_irYoeVvmhicN6bAOSx3aPqIdU5AoPgj8SBPuEOpCdZAX8TGseIcHrhPhQ2PN0fpLh30-0S5j_v28hboBekLahFy0Rf7sOIQLwXfK5DeAHoJuqZsiekRjL3FFhSIO_cKkuI" alt=""><figcaption></figcaption></figure>

<figure><img src="https://lh3.googleusercontent.com/Ogy4r3jdsUesmBVJjhLhHCohS9Dcfdrs1SgSjVGLijQMHKw7fqkd5dktzRsY8F0L7HXUDdwrFoE28BybVt17wY1AWw8fFASmJqd_b1xjcgVGBXacoSYa9OclZwGlqbLBVxiokTF-JtYNcVz-Ty-SRo0" alt=""><figcaption></figcaption></figure>

Several LoRA models will be displayed. Select the one you want to use.

4\. Each LoRA model has a "Trigger Word." Ensure your prompts include the specific LoRA's trigger word, which is usually added automatically.

For example, if you choose "KsmRm," it will show \<lora:KsmRm:1>.

<figure><img src="https://lh5.googleusercontent.com/NAOTPoZIGGKbOPQHxBtNqTaC6Fvmz68ABYKqsO5YcHQwWkSA2yDn_sQONgfbX6n4UgTtYScNG9RzPnlqFqkjBFD5i2WgfEBFR6JLKeAwmu6sOJ_uhR5qur8d00WZsiCyrCzis5IbFBiHxex1fnT_Snk" alt=""><figcaption></figcaption></figure>

5\. Add the text or description for the image you want to create after the LoRA's trigger words.

<figure><img src="https://lh5.googleusercontent.com/Cie6sBdryTVvu1e9MkwmTy66IDwHBACV5lEZAdJtF3pSOpSglFZC7CZD0Ad4UVhFN5x3QBvCZ-3fU9QidnzqOIVIoFxB6fd6MShrZqFPeYKv5HIbDoqbHtlMieffdYZyjK_YsCfkbQ8ZS_rUJhS7vN8" alt=""><figcaption></figcaption></figure>

Congratulations! An image has been generated from your forked Stable Diffusion Space using a LoRA model.

#### Note:

If you have not previously added any models and now wish to include additional ones, please redeploy your Space through selecting new hardwares after following the steps outlined in How to Add More Models.

Once the redeployment is complete(almost 30 minutes), continue by following the guidance provided in [**Install LoRA Extensions**](#step-2-install-a-lora-model-into-automatic1111) and [**Set Up LoRA Models**](#step-3-set-up-lora-models) once more to ensure the successful integration of your newly added models and guarantee their effective functioning within your Space.

### Reference

* Special thanks to[ AUTOMATIC1111](https://github.com/AUTOMATIC1111/stable-diffusion-webui.git) for the support.
* [Stable Diffusion: What Are LoRA Models and How to Use Them?](https://softwarekeep.com/help-center/how-to-use-stable-diffusion-lora-models)
* [What are LoRA models and how to use them in AUTOMATIC1111](https://stable-diffusion-art.com/lora/)


# How to Integrate Stable Diffusion via Inference API

This tutorial guides you on how to integrate the Stable Diffusion via inference API into your products.

#### Step 1: Obtain the API Endpoint Link

1.Visit the [Stable Diffusion Base Space](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Stable-Diffusion-Base-LoRA/app), or fork it to build your own Stable Diffusion Space following this [Guide](/spaces/fork-space).

2.Click on “Click here to deploy in a new tab", and copy the URL.This is your API endpoint link. Save it for later use.

<figure><img src="/files/cbPQNWwBw4a3xRgiv64d" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/RquXd1lqLmhtQ8KdWvoR" alt=""><figcaption></figcaption></figure>

#### Step 2: Access the API Documentation

The API provides detailed documentation for various image generation tasks. You can access the internal docs via the `/docs` endpoint : `https://<API_ENDPOINT>/docs`

Note: Replace `<API_ENDPOINT>` with the URL obtained in Step 1.

<figure><img src="https://lh6.googleusercontent.com/xnKGJr5ElE3LVRCP3T1IVlbZPEeMZ-BawjCpE5sz8ILddpQHBq4A32Pc38Q-mD5qtLk-fhdCq5ssleS6pRgt0DYt5F1KuRN5brCx7y4r7ztcSedvmIoPojCS4hfCsA9z5RBF8f3SwHZOiIDR2lYYinM" alt=""><figcaption></figcaption></figure>

This enables you to review the API's capabilities and endpoints. The key endpoints to focus on are `/sdapi/v1/txt2img` and `/sdapi/v1/img2img`.&#x20;

<figure><img src="https://lh6.googleusercontent.com/SC53fhku3MyD2V15eO-pLUKIgFP1oNU6bngaV2gxXpg_60tSkqgy2wP1rnbHgi-jdNTBNVrMtBsoiyh_baJclxX0zbIBPmragXyKiKsP3BKsj7120m2Ay_dNlkuVjkBhkPShpiUdq1g60_3GxLpVx6I" alt=""><figcaption></figcaption></figure>

In this guide, we'll focus on `/sdapi/v1/txt2img`.

#### Step 3: Construct Your Payload

When you expand that tab  `/sdapi/v1/txt2img` , it gives an example of a payload to send to the API.

<figure><img src="https://lh3.googleusercontent.com/0xl60Jb99aBorngVJlTckJT5T1s78V6MZ6FPUBmQC9nUjulfoaNwiAzzmlo9zg_v8urKZOKRk1DlaJXpWMHZi0r9w_cAEt09wDiK4IELBfliXiB1uzwQNgovgy_vvnE9un5LWQXKx3F1LzXkShKLT28" alt=""><figcaption></figcaption></figure>

You can include as few or as many parameters as needed in the payload. The API will use defaults for anything not specified.

Here's how you can construct a payload:

```
payload = {
    "prompt": "apple",
    "negative_prompt": "red",
    "sampler_name": "DPM++ 2M Karras",
    "seed": 985454925,
    "cfg_scale": 7,
    "steps": 20,
    "width": 512,
    "height": 512,
}
```

#### Step 4: Make a Request

You can send your payload to the API using a `POST` request. Replace `<API_ENDPOINT>` with the URL obtained in Step 1.

```
import json
import requests
import io
import base64
from PIL import Image

url = "https://<API_ENDPOINT>"
username = 'admin'
password = 'admin1234'

# Encode the username and password in Base64
credentials = f'{username}:{password}'
credentials = base64.b64encode(credentials.encode()).decode()

headers = {
    'Authorization': f'Basic {credentials}',
    'Content-Type': 'application/json'
}

response = requests.post(url=f'{url}/sdapi/v1/txt2img', json=payload, headers=headers)
```

#### Step 5: Retrieve the Image

The API's response contains three entries: images, parameters, and info. To retrieve the generated image, follow these steps:

```
r = response.json()

# 'images' is a list of base64-encoded generated images
image = Image.open(io.BytesIO(base64.b64decode(r['images'][0]))
image.save('output.png')
```

#### Sample Code&#x20;

A sample code that should work can look like this:

```
import json
import requests
import io
import base64
from PIL import Image

url = "https://fk5ge5uhhu.mars.nebulablock.com"
username = 'admin'
password = 'admin1234'

# Encode the username and password in Base64
credentials = f'{username}:{password}'
credentials = base64.b64encode(credentials.encode()).decode()

headers = {
    'Authorization': f'Basic {credentials}',
    'Content-Type': 'application/json'  # Adjust content type if necessary
}

payload = {
    "prompt": "apple",
    "negative_prompt": "red",
    "sampler_name": "DPM++ 2M Karras",
    "seed": 985454925,
    "cfg_scale": 7,
    "steps": 20,
    "width": 512,
    "height": 512,
}
response = requests.post(url=f'{url}/sdapi/v1/txt2img', json=payload, headers=headers)

r = response.json()

image = Image.open(io.BytesIO(base64.b64decode(r['images'][0])))
image.save('output.png')
```

### Additional Notes

Lagrange allows you to switch between different models for image generation. This section outlines how to check the available models and how to change models based on your preferences.

#### 1. Checking Available Models

Before changing models, you should explore the models available. Use the following method to obtain a list of models:

```
import json
import requests
import base64

url = "https://fk5ge5uhhu.mars.nebulablock.com"
username = 'admin'
password = 'admin1234'

# Encode the username and password in Base64
credentials = f'{username}:{password}'
credentials = base64.b64encode(credentials.encode()).decode()

headers = {
    'Authorization': f'Basic {credentials}',
    'Content-Type': 'application/json'  # Adjust content type if necessary
}

response = requests.get(url=f'{url}/sdapi/v1/sd-models', headers=headers)
print(json.dumps(response.json()))
```

The above code sends a `GET` request to the `/sdapi/v1/sd-models` endpoint, providing you with a list of available models.

```
[ { "title":"chilloutmix-Ni.safetensors [7234b76e42]", "model_name":"chilloutmix-Ni", "hash":"7234b76e42", "sha256":"7234b76e423f010b409268386062a4111c0da6adebdf3a9b1a825937bdf17683", "filename":"/stable-diffusion-webui/models/Stable-diffusion/chilloutmix-Ni.safetensors", "config":null }, { "title":"v1-5-pruned-emaonly.safetensors [6ce0161689]", "model_name":"v1-5-pruned-emaonly", "hash":"6ce0161689", "sha256":"6ce0161689b3853acaa03779ec93eafe75a02f4ced659bee03f50797806fa2fa", "filename":"/stable-diffusion-webui/models/Stable-diffusion/v1-5-pruned-emaonly.safetensors", "config":null } ]
```

#### 2. Changing the Model

You can change the model used for image generation by specifying a new model checkpoint using the `/sdapi/v1/options` endpoint.&#x20;

Follow these steps:

**Step1: Define the settings you want to change in the payload.**&#x20;

For example:

```
import json
import requests
import base64

url = "https://fk5ge5uhhu.mars.nebulablock.com"
username = 'admin'
password = 'admin1234'

# Encode the username and password in Base64
credentials = f'{username}:{password}'
credentials = base64.b64encode(credentials.encode()).decode()

headers = {
    'Authorization': f'Basic {credentials}',
    'Content-Type': 'application/json'  # Adjust content type if necessary
}

payload = {
    "sd_model_checkpoint": "v1-5-pruned-emaonly.safetensors [6ce0161689]",
}

```

Step 2: Send a `POST` request to the `/sdapi/v1/options` endpoint with your option payload and appropriate headers:

```
response = requests.post(url=f'{url}/sdapi/v1/options', json=payload, headers=headers)
print(json.dumps(response.json()))
```


# Diffuser/Transformer

#### About Diffuser

Diffusers is the go-to library for state-of-the-art pretrained diffusion models for generating images, audio, and even 3D structures of molecules. Whether you’re looking for a simple inference solution or want to train your own diffusion model, Diffusers is a modular toolbox that supports both.

#### About Transformer

Transformers provides APIs and tools to easily download and train state-of-the-art pretrained models. Using pretrained models can reduce your compute costs, carbon footprint, and save you the time and resources required to train a model from scratch.


# How to Integrate Diffuser/Transformer

### How to Fork the Space and Deploy it:

1\. Visit \[<https://lagrange.computer/spaces>] and log in to your account

2\. Visit the [Base Space](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Stable-Diffusion-Base-LoRA/app), and click on the **\[Fork]** button to create a duplicate of the Base Space.

<figure><img src="https://lh6.googleusercontent.com/oRy_T_MNTSJ6bqGTJtiHK_Pw-tzBLhY3r6e1UFzPxxxxD1bh5OImd22rOktVH0Cs1iO-CW1B1-a6J8JYn0GvSy_sZn1PWvuIpNg5yHGTpTI3pgWzxh9Zrm4q2eL-iyW2AAYlgOA29FZR1LN4CGw9t3c" alt=""><figcaption></figcaption></figure>

3\. You can either click on the \[**Just Fork, choose config later**] or select your preferred hardware, and proceed with the payment.

It's recommended to choose "config later" if you anticipate adding more models to your Space in the future to avoid unnecessary redeployments.

<figure><img src="https://lh5.googleusercontent.com/S2daQ_7aiKXdAxCogyBDELByzC282gzCATDRIa9vhx_0xYT8nrqYhAvu5kAvbrE5s-O1kYqzZ1jZYG9pnFYxqK8k-FfD1KFuAMh5g9GJ1GjbYtP5NxueHVCP3QUA3DO25DqUo-jSA63e6hPaJjKizzU" alt=""><figcaption></figcaption></figure>

In your forked Space, you can click the **\[Settings]** button and scroll down to the Rename section to rename your Space.

***Note:** Please note that after you change the Space name, the Space link will also be updated. Make sure to share the new link with others as needed.*

<figure><img src="https://lh4.googleusercontent.com/cdSKmw-kdgN5Zlm2mQ05GiCantlI8hbbfc1Ahc5cp6DcU6Fw4dMlftmYWJCskoq6tAl7oB5sXuUm549WhQ9EcIHxt6RLVcnTVwt-228mqOKEZ5KDiXmZintlNr3CeUKLzw5lTksOslWfjwwRFE7Mb1U" alt=""><figcaption></figcaption></figure>

### How to Change Models

In this tutorial, you will learn how to change models within your Diffuser/Transformer Space to meet your specific needs. We will be using the example of changing a model for the "Image-to-Text" task. Follow these steps:

**Step 1: Choose a New Model**

1.Visit the Hugging Face Model Hub at <https://huggingface.co/models>.

2.In the library list, select either "Transformers" or "Diffusers," depending on your requirements.

<figure><img src="/files/MguCfcRtJy0YkTgiUrcS" alt=""><figcaption></figcaption></figure>

3.In the task list, choose the specific model type you want. For this tutorial, we'll use "Image-to-Text" as an example.

<figure><img src="/files/wXJ2eso5rg7RxQV5QrZh" alt=""><figcaption></figcaption></figure>

Refine your search criteria to find a model that meets your requirements. Once you have identified the model you want to use, copy its name.

**Step 2: Update Your Lagrange Space**

1.Go to the Space that you've forked before

2.Navigate to "Files and Versions." Locate the file named "model-setting.json" and open it.

<figure><img src="/files/pCAKKRYAp30YKwGl6LoT" alt=""><figcaption></figcaption></figure>

3.Inside this JSON file, replace the existing model name with the one you copied from the Hugging Face Model Hub.

<figure><img src="/files/JGHRuskfosEjmEe7R8dK" alt=""><figcaption></figcaption></figure>

4.Save the changes to the JSON file.

5.After updating the model name, redeploy your Space following [Building Space](/mars-testnet/build-space)

Once the deployment is complete, you can access the new model through the Inference Endpoint, which has been updated with the selected model.

{% tabs %}
{% tab title="Python" %}

```python
import requests

API_URL = "https://24lhiquaxn.meta.crosschain.computer"


def query(filename):
    with open(filename, "rb") as f:
        data = f.read()
    response = requests.post(API_URL, data=data)
    return response.json()


output = query("cats.jpg")
print(output)
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
async function query(filename) {
    const data = fs.readFileSync(filename);
    const response = await fetch(
        "https://24lhiquaxn.meta.crosschain.computer",
        {
            method: "POST",
            body: data,
        }
    );
    const result = await response.json();
    return result;
}

query("cats.jpg").then((response) => {
    console.log(JSON.stringify(response));
});
```

{% endtab %}

{% tab title="cURL" %}

```url
 curl  https://24lhiquaxn.meta.crosschain.computer \
    -X POST \
    --data-binary '@cats.jpg'
```

{% endtab %}
{% endtabs %}

Click [here](https://lagrangedao.org/spaces/0xFbc1d38a2127D81BFe3EA347bec7310a1cfa2373/api-image-to-text/app) to check the Sample Space.


# Decentralized Auction Marketplace

The Decentralized Auction Marketplace is an innovative system designed to enable efficient and secure interactions between users and providers in a decentralized environment. This system utilizes smart contracts, a bidding engine, and decentralized storage to create a transparent and efficient marketplace for various tasks.

Providers in the system contribute their resources, such as storage, network bandwidth, CPU, and GPU, to offer services to users who publish tasks on the platform. These tasks are stored on decentralized storage like IPFS/Filecoin, ensuring data security and transparency.

The bidding engine manages a competitive bidding process, where providers with different resource capabilities bid on tasks. Smart contracts on the Ethereum blockchain govern the bidding rules, enforce fair competition, and ensure the security of transactions.

Upon completion of a task by the selected provider, the final results are uploaded to the decentralized storage, maintaining data integrity and tamper-proofing. The smart contract then facilitates the automatic transfer of rewards from the task publisher to the provider as compensation for their services.

In summary, the Decentralized Auction Marketplace offers a secure and efficient platform for users to outsource tasks to a global network of providers with various resources. By leveraging blockchain technology, smart contracts, and decentralized storage, the system ensures transparency, security, and fairness in the bidding process and the execution of tasks.

### Key concepts

**Bidder (Provider)**: A bidder, also known as a provider, is a participant in the marketplace who offers their services to complete tasks. These services may include storage, network bandwidth, CPU, and GPU resources. Bidders are typically composed of blockchain nodes worldwide, and they actively participate in the competitive bidding process to secure tasks. Once assigned a task, bidders work to complete it to the best of their abilities, and the one with the best performance is rewarded by the task publisher.

**Publisher (User)**: A publisher, also known as a user, is an individual or organization that creates tasks in the marketplace. Publishers are responsible for defining the tasks, providing necessary details, and setting the rewards. They rely on the Decentralized Auction Marketplace to find suitable providers (bidders) to complete their tasks. Once the bidding process is complete and a provider has successfully delivered the task, the publisher rewards the provider through the smart contract system.

**Decentralized Storage**: Decentralized storage systems like IPFS/Filecoin are used to store tasks and their associated data. This ensures that the data remains secure, transparent, and tamper-proof, while also allowing for easy access by authorized parties.

**Bidding Engine**: The bidding engine manages the competitive bidding process, where providers bid on tasks based on their resource capabilities and offered prices. This component ensures that tasks are allocated to providers in a fair and efficient manner.

**Smart Contracts**: Smart contracts are self-executing contracts on the EVM blockchain that govern the bidding rules, enforce fair competition, and ensure the security of transactions. They facilitate the automatic transfer of rewards from users to providers upon task completion and manage other aspects of the bidding process.


# Auction Engine

The auction engine is a critical component of the LagrangeDAO system. It manages the bidding process for tasks, ensuring that tasks are assigned to the most suitable computing providers. Here's a breakdown of its key functionalities:

1. **Load Provider Pool**: The auction engine initially loads all active computing providers into a pool. These providers are potential bidders for tasks.
2. **Place Bid**: When a task is open for bidding, the auction engine allows a computing provider (bidder) to place a bid on the task. The bid is only successful if the task is currently accepting bids, the bidder has not already placed a bid, and the bidder's collateral is sufficient.
3. **Load Tasks from Redis**: The auction engine fetches all tasks from Redis that are in a state where they can accept bids. It also handles state transitions for tasks, such as moving a task from the 'accepting\_bids' state to the 'bidding\_closed' state when the bidding period ends.
4. **Select Bidders**: The auction engine selects bidders based on certain criteria. For example, it might select the bidders with the highest collateral.
5. **Run Bidding Process**: For each task that is open for bidding, the auction engine runs the bidding process. It allows the selected bidders to place their bids on the task.
6. **List Tasks Available for Bidding**: The auction engine can provide a list of all tasks that are currently open for bidding.

The auction engine is designed to be fair and efficient, ensuring that tasks are distributed evenly among computing providers and that the bidding process is competitive. It plays a crucial role in the operation of the LagrangeDAO network.

&#x20;The data structure for each task in the platform includes:

* uuid: A unique identifier for the task.
* status: The current status of the task (e.g., open, closed, in progress, completed).
* task\_detail\_cid: A content identifier for the task details, stored on a decentralized storage system like IPFS.
* type: The type or category of the task.
* reference\_id: A reference ID for linking related tasks or resources.
* name: The name or title of the task.
* leading\_job\_id: The ID of the job currently in the leading processing status, used for tracking purposes.
* created\_at: The timestamp when the task was created.
* updated\_at: The timestamp when the task was last updated.
* user\_id: The ID of the user who created the task.

When a user publishes a task, multiple providers (blockchain nodes worldwide) can bid on the task. The Bidding Engine evaluates these bids and assigns the task to several bidders with the potential to complete the task effectively. Once they complete the task, the Bidding Engine assesses the quality of their work, updating the leading\_job\_id as necessary to keep track of the best-performing bidder.

Finally, the provider who delivers the highest-quality work is marked as successful and receives a reward from the task publisher. By employing this mechanism, the Bidding Engine promotes efficiency and transparency in the Decentralized Bidding Marketplace, ensuring that tasks are matched with the most suitable providers and completed to the highest standards.

### Autobid

The Decentralized Bidding Marketplace can be configured to include an auto-bid mode for providers, which allows them to automatically participate in all bids without manual intervention. This feature can be particularly useful for providers who want to streamline their bidding process and maximize their chances of securing tasks.

To enable the auto-bid mode, providers need to set up their capability and resource availability for bidding. This information includes the type of resources they can offer (such as storage, network bandwidth, CPU, and GPU), their capacity for each resource, and any other relevant details that may impact their ability to complete tasks.

When auto-bid mode is enabled, the Bidding Engine automatically pushes tasks to the provider based on their configured capabilities and resource availability. The Bidding Engine evaluates the provider's suitability for each task and includes their bid in the competitive bidding process. This automatic participation ensures that providers have a constant presence in the marketplace and can secure tasks that match their expertise and resources.


# Bidding Task State Machine

The bidding task state machine is a system designed to manage the bidding process for tasks, taking into account task details such as price and timeout. In this setup, each task allows a maximum of three bidders to compete simultaneously, with each bidder being assigned a job to complete.

Bidders have the ability to set a limit on the number of bids they can process at the same time. This feature prevents them from accepting new bids once they reach their specified limit, enabling bidders to effectively manage their workload and participate in multiple tasks without overextending themselves.

<figure><img src="/files/QxmcubT5kKSfLwlHaBWq" alt=""><figcaption></figcaption></figure>

### States

The Bidding State Machine has several predefined states:

1. **created**: This is the initial state when a task is first created. The task stays in this state until bidding is opened.
2. **accepting\_bids**: In this state, the task is open for bidders to place their bids. The task remains in this state until bidding is closed, the bid is cancelled, or the bid fails.
3. **bidding\_closed**: This state indicates that the bidding process for the task has ended. The task transitions to this state from the 'accepting\_bids' state. From here, the task can either be marked as 'submitted' or 'failed'.
4. **submitted**: This state signifies that the task has been submitted successfully. The task moves to this state from the 'bidding\_closed' state. Once a task is in the 'submitted' state, it can then be completed.
5. **completed**: This is the final state indicating that the task has been completed successfully. The task transitions to this state from the 'submitted' state.
6. **failed**: This state indicates that the task has failed. The task can enter this state from the 'bidding\_closed' state. If a task fails, it can be reset to the 'created' state.
7. **cancelled**: This state signifies that the bid for the task has been cancelled. The task can enter this state from the 'accepting\_bids' state. If a bid is cancelled or fails, the task can be reset to the 'created' state.

The transitions between these states are managed by the state machine, which ensures that the task moves through its lifecycle in a controlled and predictable manner.

* `open_bidding`: Transition from Created to Accepting\_Bids.
* `close_bidding`: Transition from Accepting\_Bids to Processing.
* `cancel_bid`: Transition from Accepting\_Bids to Cancelled.
* `failed_bids`: Transition from Accepting\_Bids to Cancelled.
* `complete_task`: Transition from Submitted to Completed.
* `mark_as_submitted`: Transition from Processing to Submitted.
* `mark_as_failed`: Transition from Processing to Failed.
* `reset_accepting_bids_to_created`: Transition from Accepting\_Bids to Created.
* `reset_failed_bids_to_created`: Transition from Failed to Created.

The Bidding State Machine has defined transitions between states:

### Transition Between States

1. open\_bidding: Transition from 'Created' to 'Accepting\_Bids'.
2. close\_bidding: Transition from 'Accepting\_Bids' to 'Processing'.
3. cancel\_bid: Transition from 'Accepting\_Bids' to 'Cancelled'.
4. failed\_bids: Transition from 'Accepting\_Bids' to 'Cancelled'.
5. complete\_task: Transition from 'Submitted' to 'Completed'.
6. mark\_as\_submitted: Transition from 'Processing' to 'Submitted'.
7. mark\_as\_failed: Transition from 'Processing' to 'Failed'.
8. reset\_accepting\_bids\_to\_created: Transition from 'Accepting\_Bids' to 'Created'.
9. reset\_failed\_bids\_to\_created: Transition from 'Failed' to 'Created'.

### Rules

The bidding task state machine should include the following rules:

* A bidder cannot place a bid if they have exceeded their limit on the number of jobs they can process simultaneously.
* Once a bidder has completed a job, they cannot be assigned any further jobs on the same task.

If the task is cancelled, all bids and jobs associated with the task are cancelled as well


# Reputation System

The Lagrange reputation system is designed to assess and quantify the trustworthiness and reliability of individual computing providers in the Lagrange computing network. It helps the bidding engine make informed decisions when assigning tasks to providers and promotes accountability within the network. Such a reputation system considers the recent performance, behavior, and feedback received by the providers to establish their reputation scores in a dynamic way.

In this system, each computing provider is assigned a reputation score between 0 and 100 that reflects their past performance and interactions within the network. The reputation score can be based on various factors, including success rate, reachability, and region. Higher reputation scores generally indicate more reliable and trustworthy providers, increasing the likelihood that they will receive tasks they can be rewarded for completing. Likewise, providers with lower reputation scores may need to improve their performance to attract more users and enhance their reputation.

## Scoring Computing Providers

The scoring method takes into account various factors to assign scores to computing providers. These factors include:

1. Reliability and Uptime: Providers that consistently maintain high availability and uptime, minimizing downtime and interruptions, are considered more reliable.
2. Task Completion Rate: Providers that consistently complete assigned tasks and return a valid and excellent result can increase their success rate, further increasing their overall score.
3. Region: The region score of a provider aims to reflect the relative scarcity or abundance of providers in a specific region and adjusts the score accordingly. By assigning a higher region score to providers in regions with fewer competitors, the scoring system incentivizes the establishment and growth of computing infrastructure in underserved or less populated areas.

## The Score Equation

```
Overall Reputation Score = Base Score + 65 * Weekly Score + 25 * Monthly Score + 10 * Region Score
```

**Base Score:** The initial, and thus base, score that everyone will start with assuming the other weighted factors are unitialized and/or 0.

**Weekly Score:** Reflects the provider's performance on a weekly basis. Given the highest weighting to emphasize recent performance. Notice that this score can be negative if recent performance is very poor!

**Monthly Score:** Reflects the provider's performance on a monthly basis. This score can also be negative if a provider behaves poorly during the period.

**Region Score:** Takes into account the provider's location and the number of competitors in that region.

Overall, a provider's reputation score will still be capped between 0 and 100.

## How is Weekly and Monthly Scores Calculated?

#### Monthly example:

```
Monthly Score = 50 * Monthly reachability + 50 * Monthly success rate
```

The equation for a weekly score is the same except that the time period of which reachability and success rate are calculated will obviously differ.

### Reachability:

```
(# of succesful requests - # of failed requests) / total # of requests made to provider by server
```

The Lagrange server will periodically send a ping to each provider. If the provider receives the ping and the server receives a response back, then the request will be saved as a success. Otherwise, the request will be saved as failed.

### Success Rate:

```
(# of completed tasks - # of failed/incomplete tasks) / total # of tasks assigned to provider
```

This equation provides a quantitative measure of a provider's performance and success in completing assigned tasks. Clearly, higher success rate indicates a higher level of reliability, efficiency, and effectiveness in task completion. On the other hand, a lower success rate may indicate room for improvement or potential issues in fulfilling assigned tasks.

## How is Region Score Calculated?

```
Region Score = 1 - ( # of providers in the region / total # of providers ) 
```

So, if for example 20% of providers globally reside in North America, then a provider in this region would get a region score of `1 - 0.2 = 0.8`. Once again, by assigning a higher region score to providers in regions with limited competition, the scoring system addresses potential imbalances in service distribution and also promotes regional growth.


# Security


# Access Tokens

## User Access Tokens

### &#x20;What are User Access Tokens?

User Access Tokens are the preferred way to authenticate an application or notebook to Lagrange  services. You can manage your access tokens in your [settings](https://lagrange.computer/personal_center/setting/tokens).

### External Access Tokens

The External Access Tokens  refers to the tokens that computing providers use to access or integrate with external services, such as chatGPT, during the execution of a task. This access token is stored in the computing provider's profile on Lagrange.

Here's a general flow of how it works:

1. **Storing the Access Token**: The Computing Provider stores the External Access Token (obtained from a service like OpenAI's chatGPT) in their Lagrange Profile under "setting/tokens", which is a part of the Lagrange Hub.
2. **Task Assignment**: The Auction Engine within the Lagrange Hub assigns a task that requires an External Access Token to the Computing Provider.
3. **Token Retrieval**: The Computing Provider retrieves the External Access Token from its Lagrange Profile.
4. **Environment Setup**: The Computing Provider loads the External Access Token into the runtime environment as an environment variable.
5. **Task Execution**: The Computing Provider executes the task using the required resources. If the task involves the external service, it accesses the service using the External Access Token.
6. **Accessing the External Service**: The External Access Token is used to authenticate the Computing Provider's requests to the External Service and gain access to the resources or capabilities needed to complete the task.<br>

<figure><img src="/files/3ABjt3KRK9auUIg9Jefm" alt=""><figcaption></figcaption></figure>

In this diagram:

1. The Computing Provider stores the External Access Token (obtained from a service like OpenAI's chatGPT) in their Lagrange Profile under "setting/tokens", which is a part of the Lagrange Hub.
2. The Auction Engine within the Lagrange Hub assigns a task that requires an External Access Token to the Computing Provider.
3. The Computing Provider retrieves the External Access Token from its Lagrange Profile.
4. The Computing Provider loads the External Access Token into the runtime environment as an environment variable.
5. The Computing Provider executes the task using the required resources. If the task involves the external service, it accesses the service using the External Access Token.
6. The External Access Token is used to authenticate the Computing Provider's requests to the External Service and gain access to the resources or capabilities needed to complete the task.

The usage of access tokens as environment variables can help ensure a secure, efficient, and flexible execution environment. This mechanism allows the computing providers to seamlessly integrate with various external services as required by their tasks, enhancing the capabilities and versatility of the Lagrange network.


# Token

Lagrange Token is the utility token for purchasing computing resources.

The Lagrange token has 3 stages:

1. [Lagrange Testnet](#lagrange-testnet-token)
2. [Swan Testnet](#swan-testnet-token)
3. [Swan Mainnet](#swan-mainet-token)

#### Lagrange Testnet&#x20;

Testnet: SepoliaETH

Lagrange Testnet Token (LAG) is used on langrage testnet. The first time it is deployed is during the Mars Testnet. LAG testnet token does not has value and can get it from the faucet.

#### Swan Testnet&#x20;

Testnet: tETH

Swan Testnet Token (Swan) is used on Swan Testnet. The Swan Testnet  is designed to Launch in Q4 2023.

#### Swan Mainnet

Bsse Chain: ETH

Swan is a L2 blockchain on Ethereum with Rollup technology.

Swan Mainet Token is used by swan mainnet, when swan mainnet launches, user can perform a one-time swap at 1:1 with Lagrange mainnet Token. The total supply is 1,000,000,000.


# Mars Testnet

The Intro of the Lagrange Mars Testnet Campaign

Welcome to the Lagrange Mars Testnet Campaign 2023!

We are excited to invite you to be a part of the Lagrange Testnet, interacting with Lagrange firsthand and experiencing the groundbreaking features and functionalities Lagrange has developed for the future of Web3.

🗓️ Campaign Duration: 14th August, 00:00 (EST) - 17th September, 23:59 (EST)

### Event Website

[http://mars-testnet.lagrangedao.org](https://t.co/HHT2ek6Wr8)&#x20;

### Task List: &#x20;

* Deploy Computing Provider
* Run  Spaces
* Use  Spaces

## Mission

Lagrange's Mars Testnet is the first attempt to utilize enormous computing and storage resources of Filecoin, Chainlink, BNB Chain, and other blockchains for Web3 developers.

Over the course of four weeks, we will utilize decentralized computing power from different blockchains to create a captivating scene on Planet Mars, including:

* Landscape
* Creatures
* Vehicles, Spaceship
* Buildings and live scene
* CG/Short film

Partners from the realms of AI, gaming, and the metaverse are welcome to join us in this ambitious endeavor by contacting us at <team@filswan.com>.

## Goals

* Harness the power of 100 GPUs to generate 1 million images.
* Validate large-scale GPU computing on the Lagrange Network.
* Explore the adaptation of models such as Stable diffusion, Lora, and Dall-E for image generation.
* Solicit developer feedback on space building and datasets.
* Multichain Payment and debug on the payment channel.
* Validate Lagrange Network's new GPU marketplace.
* Collaborate with partners in AI, gaming, and the metaverse.
* Engage our community in the AIGC including images and scenes.
* Attract AI and ML enthusiasts/ experts to the Lagrange Network community.

## Tasks and Rewards:

1. [**Computing Provider Setup Task**](/mars-testnet/setup-computing-provider)**:**

Set up a Computing Provider with the specified requirements and keep it online during the Campaign to split **500,000 LAG** tokens based on GPU hours, with the Top 1 Computing Provider winning the Golden CP privilege.

2. [**Space Builder Task**](/mars-testnet/build-space)**:**

Fork and run a Space from the provided Base Space, and share it on Twitter to have a chance to split the **300,000 LAG** token prize pool based on the popularity of the created space.

3. [**Image Creator Task**](/mars-testnet/use-space)**:**

Create at least 3 images from any Space in Lagrange following weekly themes, upload them to Multichain.Storage, and share them on Twitter to split the **200,000 LAG** token prize pool based on the popularity of the images, with top creators receiving higher rewards.

*Note: All LAG awards will be delivered in the form of NFTs, and NFT holders can claim their LAG after the TGE (Token Generated Event).*

## Workshop

Throughout the campaign period, we have an exciting series of workshops lined up, where we'll delve into the use cases of Computing Provider setup, Space building, and Space using on the Lagrange platform.&#x20;

*Join us on our* [*Discord channel*](https://discord.gg/GRxpvefPmk) *and keep an eye out for more updates and detailed information about these workshops.*&#x20;

## Key Dates to Remember

* Early Birds registration closes: August 8th
* Early Birds get their documentation: August 10th
* Zealy Quest onboarding: August 8th - August 16th
* Mars Testnet Campaign: August 14th - September 17th
* Workshop series: August 14th - September 10th
* Participants selected and announced: September 20th

Get ready to level up your skills and be part of the Lagrange Mars Testnet journey! <br>


# Before You Get Started

Before you embark on your Lagrange Mars Testnet journey, make sure to follow these steps to participate seamlessly:

### Set Up Metamask

Setup your MetaMask wallet for the Polygon testnet: Ensure your MetaMask wallet is configured to work with the Polygon testnet. You can find [guides](https://filswan.medium.com/how-to-add-polygon-mumbai-testnet-to-metamask-16a11db91214) on how to do this online.

```
Network Name: Mumbai Testnet
New RPC URL: https://rpc-mumbai.maticvigil.com/
Chain ID: 80001
Currency Symbol: MATIC
Block Explorer URL: https://mumbai.polygonscan.com

```

### Connect to the Lagrange

Visit <https://lagrangedao.org> and connect your MetaMask

#### Fund Your Wallet with test MATIC Tokens

Visit the [Polygon Testnet Faucet](https://faucet.polygon.technology/). Paste your address to the faucet website and get some test MATIC tokens sent to your wallet for exploring functions on Lagrange.

Please note that the function is on the Polygon Testnet environment and speed times may differ compared to mainnet usage.

#### Claim test LAG Tokens from Discord Faucet[​](https://docs.bnbchain.org/docs/bsc-faucet#claim-tbnb-tokens-from-discord-faucet)

To get some test LAG tokens of Lagrange testnet for testing purposes, you can join the discord and go to the [**testnet-faucet**](https://discord.gg/4VDX4nPZpb) channel under the **Mars - Testnet** section. There you can claim your test LAG token for free.

1. Type the command $faucet {your-wallet-address}.
2. Switch to the Mumbai Testnet, import tokens into your wallet, and check your balance.

`Token contract address:`

`0xD36e888b351F5AD1dFF8c609af3D1010ECA7e23b`

<br>


# Computing Provider Setup

This is a guide to Computing Provider

🗓️ **Event Period：** 14th August, 00:00 (EST) - 17th September, 23:59 (EST)

## Rules

### **How to Participate:**

1\. Follow the [instructions](https://github.com/lagrangedao/go-computing-provider/tree/mars-testnet) to set up a Computing Provider and keep it online during the Campaign.

* Possess a public IP
* Have a wildcard domain name (\*.example.com)
* Have an SSL certificate
* Have at least one GPU
* At least 8 vCPUs
* Minimum 50GB SSD storage
* Minimum 32GB memory
* Minimum 50MB bandwidth
* Here are the GPUs we recommend:
  * T4, RTX 4090, 3090Ti, 3090, 3080Ti, 3080, 3060Ti, 2060, 2070, 2080, 2080Ti, A100, H100, A4000

2\. Check the [Dashboard](https://provider.lagrangedao.org/provider-status) to confirm that your Computing Provider is running during the campaign period.

3\. Provide feedback on the process, documentation, bugs, and improvement ideas in our [Discord Channel](https://discord.gg/qHEEyQTECX).

4\. Submit the [form](https://docs.google.com/forms/d/e/1FAIpQLSf0JRi18xsp_YCoQKPuE0azYLDDNwAXBMNIeqwXFMgqVljU1Q/viewform?usp=sf_link) here with the required details.

#### **How to Be Eligible:**

* Eligible Computing Provider should have at least one Space that has been deployed to it and keep the Space running during the Campaign.
* The [form](https://forms.gle/YyzotPhHqx4DmCmy9) must be submitted upon task completion.

#### **Rewards:**

* All eligible Computing Providers can split **500,000 LAG**. Rewards will be assigned based on GPU hours as a percentage of the total GPU hours.
  * Your GPU hours: the sum of the duration of your GPUs that’s been used for running Space
  * Total GPU hours: the sum of the duration of all GPUs that’s been used for running Space
* The Top 1 wins the **Golden CP privilege**

## Tutorial

Refer to [Broken mention](broken://pages/gfo4MQt6YxxxyrlqBMHU)

## FAQ

#### Q: How can I know if the status of the computing provider is normal?

**A**:&#x20;

Run the following command:

{% hint style="info" %}
***\*Note: Please replace\*\*\*\* ****`<YOUR_MULTI_ADDRESS_IP>:<PORT>`**** \*\*\*\*with your actual multi-address IP and port.***
{% endhint %}

```
curl --location --request POST 'http://<YOUR_MULTI_ADDRESS_IP>:<PORT>/api/v1/computing/lagrange/jobs' \
--header 'Content-Type: application/json' \
--data-raw '{
"uuid": "5641877b-dc94-469a-bb3b-ecab6d10f7dd",
"name": "Job-5641877b-dc94-469a-bb3b-ecab6d10f7dd",
"status": "Submitted",
"duration": 900,
"job_source_uri": "https://api.lagrangedao.org/spaces/51d6abbb-f928-43e4-91fd-79e93e2b276f",
"storage_source": "lagrange",
"task_uuid": "92cd5595-9789-4af3-9100-7c7e4aacb456"
}'
```

After running this command, wait for 3-5 minutes, and then execute&#x20;

<pre><code><strong>kubectl get ing -n ns-0x6091b2f5678952cafbf02755d78973ebff302e11
</strong></code></pre>

Find the hosts corresponding to the name `ing-minesweeper` and ensure that the domain can be accessed in a browser to confirm its normal status.

<img src="/files/KCBvCM2My872xsA0adO4" alt="" data-size="original">

#### Q: My node has been running for so long, yet the uptime is 0%.

**A**:

1\. Run the following command:

{% hint style="info" %}
***Ensure that\*\*\*\*  ****`<YOUR_MULTI_ADDRESS_IP>`**** \*\*\*\*is the Public IP.***
{% endhint %}

```bash
curl http://<YOUR_MULTI_ADDRESS_IP>:<PORT>/api/v1/computing/host/info
```

2\. Compare the returned result with the example provided below. If they are different, you should review your port mappings.

Example result:

```json
{"status":"success","code":"","data":{"swan_miner_version":"","operating_system":"linux","architecture":"amd64","cpu_cores":48}}
```

3\. If your port mappings are correct and the result matches the example, then proceed to check the configuration file of the computing provider.&#x20;

Ensure that the `MultiAddress` is set exactly as `"/ip4/<public_ip>/tcp/<port>"`.

#### Q: Which ports need to be mapped?&#x20;

**A**: Here are the ports you need to map

1\. You need to map the CP's internal IP and its port (default 8085), as well as the public IP and port.

2\. Map your wildcard domain (\*.example.com) to your public IP.&#x20;

3\. Additionally, you need to map port 80 of your internal IP to port 80 of your public IP, as well as port 443 of your internal IP to port 443 of your public IP.

#### Q: Where should I create the API key?

**A**: you must use the API of <https://multichain.storage,> and login in it using Polygon mainnet wallet.

#### Q: What are the requirements for SSL certificates needed in CP?&#x20;

**A:** Please use certificates issued by trusted Certificate Authorities (CA). Currently, certificates generated by Certbot are not functioning properly.&#x20;

Otherwise, the application won't be displayed correctly on the Space App page.

#### **Q: Is it possible to use a port other than 80 and 443 in the wildcard domain(\*.exmaple.com)?**

**A**: No, it is not possible.

#### Q: Is the "pod" used for communication, and "Calico" is used to manage this communication within the cluster?&#x20;

**A**: Both are used for intra-cluster communication. You can use one of these approaches.

#### Q: If someone didn't apply for early bird, can they still join and run the computing provider tasks?

**A**: Of course, they can also follow the [instruction](broken://pages/gfo4MQt6YxxxyrlqBMHU) to set up a Computing Provider.

#### Q: Can I move my computing provider to a new one while maintaining my previous server? Will this reset my uptime?

**A**: Yes, you need to move  `.swan_node` to the new server. The uptime will not be reset.


# Building Space

This is a guide to Space Builder

🗓️ **Event Period：** 14th August, 00:00 (EST) - 17th September, 23:59 (EST)

## **Rules**

#### **How to participate:**

1\. Fork a space from the provided [Stable Diffusion Base Space](https://lagrangedao.org/spaces/0x6091b2f5678952cAfbf02755D78973EBff302e11/Stable-Diffusion-Base-LoRA/card) and successfully run it.

2\. Update your forked Space following the [Tutorial](#tutorial).

3\. Share your Space on Twitter

* Content must be in English.
* Content must be shared on Twitter, and must tag [@lagrangedao](https://twitter.com/lagrangedao) and [@0xfilswan](https://twitter.com/0xfilswan)

4\. Submit the [form](https://forms.gle/YyzotPhHqx4DmCmy9) here with the required details, including

* Link to your Space
* Link to the tweet you shared

#### **How to Be Eligible:**

* Eligible Space Builders shall build at least one Space that generates at least one image and remains operational for the duration of the event.
* The [form](https://forms.gle/YyzotPhHqx4DmCmy9) must be submitted upon task completion.&#x20;

#### **Rewards:**

* All eligible Space Builders have a chance to split the prize pool of **300,000 LAG** tokens based on the popularity of the space you build. The more popular your space, the greater your reward!
* Prizes:
  * Top 1: 20,000 LAG
  * Top 2-5: 10,000 LAG each
  * Top 6-10: 4,000 LAG each
  * Top 11-50: 2,000 LAG each
  * All other participants (rank 51 and beyond) will share the remaining 140,000 LAG pool.

*Note: The ranking will be based on the popularity of the space they build.*

## Tutorial

### Table of Content

* [Introduction](#introduction)
* [How to Fork the Base Space and Rename it](#how-to-fork-the-base-space-and-rename-it)
* [How to Add More Models (optional)](#how-to-add-more-models)
* [How to Get Your Space Running](#how-to-get-your-space-running)
  * [Deploy the Stable Diffusion Web UI (Automatic1111)](#step1-deploy-the-stable-diffusion-web-ui-automatic-111)
  * [Install LoRA Extensions](#step-2-install-a-lora-model-into-automatic1111)
  * [Set Up LoRA Models](#step-3-set-up-lora-models)
* [Reference](#reference)

### Introduction

This tutorial guides you on how to complete[ Task 2: Space Builder Task](https://github.com/lagrangedao/community/blob/main/Mars-Testnet/Lagrange-Mars-Testnet-Campaign.md), to fork and run a Stable Diffusion Space. It covers the deployment of Stable-diffusion in Lagrange Space, adding LoRA models to Automatic1111 for image generation, and further customizing your Space with additional models.

What is Stable Diffusion: Stable Diffusion is a state-of-the-art text-to-image model that generates an image from text.

What is Space: Space is a simple way to host ML demo apps on Lagrange.

What is LoRA: LoRA (Low-Rank Adaptation) is a training technique for fine-tuning Stable Diffusion models. and LoRA models are specific versions of the Stable Diffusion model that have undergone fine-tuning.

What is Automatic111: Stable Diffusion web UI (AUTOMATIC1111 or A1111 for short) is the de facto GUI for advanced users.

#### How to Fork the Base Space and Rename it:

1\. Visit \[<https://lagrangedao.org/spaces>] and log in to your account

2\. Visit the[ Stable Diffusion Base Space](https://lagrangedao.org/spaces/0x6091b2f5678952cAfbf02755D78973EBff302e11/Stable-Diffusion-Base-LoRA/card), and click on the \[Fork] button to create a duplicate of the Base Space.

<figure><img src="https://lh4.googleusercontent.com/UJnbM8oLVJXDjWZZkxQ7fDCek29pVJVBGxoAmvMUyhRzzX-z_WtvKNWKwzYH3xxQZjlwI9UV5Tl3hV_DjFsf6h9zRaxy6EACBGTbtvwDK2P47l8KcTDISitGLMZUdY2gy3Q7NtKejlP3Hdzhoy9xm-M" alt=""><figcaption></figcaption></figure>

<figure><img src="https://lh6.googleusercontent.com/oRy_T_MNTSJ6bqGTJtiHK_Pw-tzBLhY3r6e1UFzPxxxxD1bh5OImd22rOktVH0Cs1iO-CW1B1-a6J8JYn0GvSy_sZn1PWvuIpNg5yHGTpTI3pgWzxh9Zrm4q2eL-iyW2AAYlgOA29FZR1LN4CGw9t3c" alt=""><figcaption></figcaption></figure>

3\. You can either click on the \[Just Fork, choose config later] or select your preferred hardware, and proceed with the payment.

It's recommended to choose "config later" if you anticipate adding more models to your Space in the future to avoid unnecessary redeployments.

<figure><img src="https://lh5.googleusercontent.com/S2daQ_7aiKXdAxCogyBDELByzC282gzCATDRIa9vhx_0xYT8nrqYhAvu5kAvbrE5s-O1kYqzZ1jZYG9pnFYxqK8k-FfD1KFuAMh5g9GJ1GjbYtP5NxueHVCP3QUA3DO25DqUo-jSA63e6hPaJjKizzU" alt=""><figcaption></figcaption></figure>

In your forked Space, click the \[Settings] button and scroll down to the Rename section to rename your Space.

***Note:** Please note that after you change the Space name, the Space link will also be updated. Make sure to share the new link with others as needed.*

<figure><img src="https://lh4.googleusercontent.com/cdSKmw-kdgN5Zlm2mQ05GiCantlI8hbbfc1Ahc5cp6DcU6Fw4dMlftmYWJCskoq6tAl7oB5sXuUm549WhQ9EcIHxt6RLVcnTVwt-228mqOKEZ5KDiXmZintlNr3CeUKLzw5lTksOslWfjwwRFE7Mb1U" alt=""><figcaption></figcaption></figure>

#### How to Add More Models

If you prefer to utilize the default LoRA models provided by Base Space, you can proceed directly to the section on How to Get Your Space Running.

However, if the available models do not precisely align with your image preferences, you have the option to enhance your Stable Diffusion Space by adding more models by following the below steps.

1\. Find models you liked from[ Civitai](https://civitai.com/?query=lora) and[ Hugging Face](https://huggingface.co/models?search=lora), and get the downloading link of the model.

2\. Go to \[Files and versions] and Update the Dockerfile, you need to replace the \<model\_download\_link> and \<your\_model\_name>, then add the below command to the Dockerfile:

\# Command example:

```
RUN wget <model_download_link> -O /stable-diffusion-webui/models/Lora/<your_model_name>
```

<figure><img src="https://lh6.googleusercontent.com/JaUXPWNgWgo640KbJou5RLRtsUjc2X0LDdDZ-azOUxHzKFD2p25gLtUORnh_fxBiNvK9x3ovlkkD5vyfbDdaAN0yY2_uAxyDu6WZMnev5l7zk0XPR2mDly5qye32xdoAyvPOWHREK1IDqyH4AL-sQ84" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/RSgrtbhjSL3YxCJWfuyK" alt=""><figcaption></figcaption></figure>

#### How to Get Your Space Running

To set up your Stable Diffusion Space for generating images from textual descriptions, you must

1. deploy the Stable Diffusion Web UI, a user-friendly interface that facilitates interaction with the model. Additionally,
2. installing LoRA extensions enhances the Web UI's capabilities, enabling support for LoRA models.
3. installing the actual LoRA models to enable image generation.

#### **Step1: Deploy the Stable Diffusion web UI (Automatic 111)**

1\. Click on \[Settings] and select your preferred hardware meeting the below requirements:

* At least one GPU
* At least 8 vCPUs
* Minimum 50GB SSD storage
* Minimum 32GB memory
* Minimum 50MB bandwidth
* Here are the GPUs we recommend:
  * T4, RTX 4090, 3090Ti, 3090, 3080Ti, 3080, 3060Ti, 2060, 2070, 2080, 2080Ti, A100, H100

**Ensure you choose hardware with at least one GPU**; without it, Stable Diffusion Space won't function.

And proceed with the payment.

<figure><img src="/files/efXtT0biC9nJCptYdztQ" alt=""><figcaption></figcaption></figure>

<figure><img src="https://lh3.googleusercontent.com/ur12FW4N4N9oFzS5J5nO55B5wZMb9wHtVV6kvkC5oHumsfut9B9cDmDvSlabaezsQ9HN_7ebG9s4wwAlOHsRmB-X2laTri9PAf5228lLlCAOAexnb_LE_UXW6MXfyhryuSlZbNApJwtjwxXiU1LoKOI" alt=""><figcaption></figcaption></figure>

2\. After payment confirmation, observe the status tag of your Space. It will transition from "Waiting for Transaction" to "Deploying," and finally to "Running" once the Stable Diffusion web UI is successfully deployed on your Space.

<figure><img src="https://lh3.googleusercontent.com/GynEwa-x3Vg008tyW70OlJ11Du-WbouUPAfRhH1WKODaXMIxS6-8RsrVoXxRxgRkQMrPORtnnIkRL2W2usMpMVZNb8V6b5KMeesy_TYVsJm4lu4ikYwThdw4kie1uZWER_6VMdsxdIO5E7aCLchRTmE" alt=""><figcaption></figcaption></figure>

After a few minutes, you can access the Stable Diffusion web UI in the \[App] tab of your Space.

\*Note: Do not panic if you encounter a "404" or "502" error while accessing the web UI. These errors indicate that the web UI is currently deploying, and the process typically takes around 1-10 minutes to complete.

#### **Step 2: Install a LoRA Model Into Automatic1111**

Before using LoRA models in your Stable Diffusion Web UI, you need to install the LoRA extension.

1\. Click on the \[App] tab to Launch the Stable Diffusion Web UI in the space.

<figure><img src="https://lh3.googleusercontent.com/bv9DMnddVoAL2FaT_iw1_Izp87oy4GbpG5hjnFuICcjm62YrmND_WqicTYocsGmS-hYeht1j6d0FjhE0x_qD3su3OOsGJz8rnlkgj3F8xoOBqEbox-mEhv4upEzaQkU2RlnTTkKzPkZ5Yxw4hxI6FHU" alt=""><figcaption></figcaption></figure>

2\. Open the \[Extensions] tab, click on \[Install from URL], and copy the following link:

<https://github.com/kohya-ss/sd-webui-additional-networks.git>

And Click the "Install" button.

<figure><img src="https://lh6.googleusercontent.com/8KNP0TXzh5EBUFjrAVPmClMgxMG1VDEI_MzoY36EBuhY5jD4KzDmChiq9QVVn8slZZxc2LfmoHcw6s0Akij5KuJvL9Y2HZ7ZgtRO-M4_x5rVaH6Vzc6dUHImD7ys7lGrkUu2gIU6t-cy66LuJwp-Mv4" alt=""><figcaption></figcaption></figure>

3\. To verify if the installation was successful, switch to the \[Installed] tab. and Click on the \[Apply and restart UI] button.

<figure><img src="https://lh3.googleusercontent.com/D34PMjWXZjDEz9mtIKJCLu6vkoUgJGsHN7Fh0FdUA30vQAIaCbI8_Q-sYh1E3qjkZRJsLjBBDo16S9diY8TMUIr_GfcBRcdOa89jTiBS0W7m9eSCX5_Zvub8Q_tnQLdiAZBQG7C7uWLq_W3GROkmFpo" alt=""><figcaption></figcaption></figure>

4\. Open the \[Settings] tab and switch to the \[Additional Networks] tab, paste stable-diffusion-webui/models/Lora in the input field of \[Extra paths to scan for LoRA models] and then click \[Apply settings].

<figure><img src="https://lh4.googleusercontent.com/ABPxubNgvGpLUgdYM0DHN3ub-h34hu0g8hLt0rdQmsujA6oDtTjt64zVPq-uVMrYGUiD6EzLcBbWV-4xgPz8CUdRNVgPowpzD87tn_NvTshfZQZZJ90q50R2bQx1FyKe2r5Kpq4MeFb5AKHjRVXc_O0" alt=""><figcaption></figcaption></figure>

<figure><img src="https://lh4.googleusercontent.com/5dVz0nAVDWgvQ7qOrPWSycUBAifZQyiyFV9fb6vV5rWrE-iNYoaLsSYx4zZIqQYTQLjzGh06yftmn_SDJujpTEUuRlaZYXFoqSOuZlqRd0-gYe-OsMg0Z6O7hpB_nHKvQWAjY0BqU8PV6Qim2Km34PI" alt=""><figcaption></figcaption></figure>

#### **Step 3: Set Up LoRA Models**

Although the LoRA Extension has been installed successfully, it's not enough to start generating images. You need to install your actual LoRA Models to the specified folder as well.

1\. Click the \[App] tab in your Space to access the launched Stable Diffusion Web UI.

2\. Choose your desired checkpoint model from the preloaded options (e.g., "chilloutmix-Ni.safetensors" or "V1-5-pruned-emaononly.safetensors").

3\. Click on the \[txt2img] tab and select the icon of "Additional Networks" under the "Generate" button, then choose \[LoRA].

<figure><img src="https://lh4.googleusercontent.com/Tj_whyH8mY6b6-7zJOtw_irYoeVvmhicN6bAOSx3aPqIdU5AoPgj8SBPuEOpCdZAX8TGseIcHrhPhQ2PN0fpLh30-0S5j_v28hboBekLahFy0Rf7sOIQLwXfK5DeAHoJuqZsiekRjL3FFhSIO_cKkuI" alt=""><figcaption></figcaption></figure>

<figure><img src="https://lh3.googleusercontent.com/Ogy4r3jdsUesmBVJjhLhHCohS9Dcfdrs1SgSjVGLijQMHKw7fqkd5dktzRsY8F0L7HXUDdwrFoE28BybVt17wY1AWw8fFASmJqd_b1xjcgVGBXacoSYa9OclZwGlqbLBVxiokTF-JtYNcVz-Ty-SRo0" alt=""><figcaption></figcaption></figure>

Several LoRA models will be displayed. Select the one you want to use.

4\. Each LoRA model has a "Trigger Word." Ensure your prompts include the specific LoRA's trigger word, which is usually added automatically.

For example, if you choose "KsmRm," it will show \<lora:KsmRm:1>.

<figure><img src="https://lh5.googleusercontent.com/NAOTPoZIGGKbOPQHxBtNqTaC6Fvmz68ABYKqsO5YcHQwWkSA2yDn_sQONgfbX6n4UgTtYScNG9RzPnlqFqkjBFD5i2WgfEBFR6JLKeAwmu6sOJ_uhR5qur8d00WZsiCyrCzis5IbFBiHxex1fnT_Snk" alt=""><figcaption></figcaption></figure>

5\. Add the text or description for the image you want to create after the LoRA's trigger words.

<figure><img src="https://lh5.googleusercontent.com/Cie6sBdryTVvu1e9MkwmTy66IDwHBACV5lEZAdJtF3pSOpSglFZC7CZD0Ad4UVhFN5x3QBvCZ-3fU9QidnzqOIVIoFxB6fd6MShrZqFPeYKv5HIbDoqbHtlMieffdYZyjK_YsCfkbQ8ZS_rUJhS7vN8" alt=""><figcaption></figcaption></figure>

Congratulations! An image has been generated from your forked Stable Diffusion Space using a LoRA model.

#### Note:

If you have not previously added any models and now wish to include additional ones, please Click on \[Redeploy] after following the steps outlined in How to Add More Models.

<figure><img src="https://lh3.googleusercontent.com/2yhRhnPCKsAX82qvk4N4tF9gVZ7CnjYLUIsrjeweTC5PCjoOY-9PE6ofpVzzYMO-_iX2eJ3xr2KJ-ScRaqOZ45n1aA8gH8s7B2wcR_aNBOuUJAJsLUi7nyPoypE8VCiKyYbg1Hm9akXFJARkqqB2Ls0" alt=""><figcaption></figcaption></figure>

Once the redeployment is complete(almost 10 minutes), continue by following the guidance provided in Install LoRA Extensions and Set Up LoRA Models once more to ensure the successful integration of your newly added models and guarantee their effective functioning within your Space.

### Reference

* Special thanks to[ AUTOMATIC1111](https://github.com/AUTOMATIC1111/stable-diffusion-webui.git) for the support.
* [Stable Diffusion: What Are LoRA Models and How to Use Them?](https://softwarekeep.com/help-center/how-to-use-stable-diffusion-lora-models)
* [What are LoRA models and how to use them in AUTOMATIC1111](https://stable-diffusion-art.com/lora/)


# Using Space

This is a guide to Image Creator

🗓️ **Event Period:** 14th August, 00:00 (EST) - 17th September, 23:59 (EST)

## Rules&#x20;

#### **How to Participate:**

1.Choose a [Stable Diffusion Space](https://lagrangedao.org/spaces) here and attempt to create some images following a theme provided by Lagrange: Mars Landscape, Mars Creatures, Mars Vehicles, Mars Buildings and live scenes.

* Each theme represents a piece of the puzzle that, when combined, will form a breathtaking scene on Planet Mars.
* Feel free to explore the [Stable Diffusion Base Space](https://lagrangedao.org/spaces/0x6091b2f5678952cAfbf02755D78973EBff302e11/Stable-Diffusion-Base-LoRA/card) and other [Stable Diffusion Spaces ](https://lagrangedao.org/spaces)updated by Space Builders.&#x20;

2.Upload your 3 best images to [Multichain.Storage](https://www.multichain.storage/) and share these images on Twitter.

3\. Submit the [form](https://forms.gle/YyzotPhHqx4DmCmy9) here with the required details, including

* Link to your image on Multichain.Storage
* Link to the tweet you shared

**How to Be Eligible:**

* Eligible Image Creator shall create at least 3 images from any Stable Diffusion Spcae in Lagrange.
* The [form](https://forms.gle/YyzotPhHqx4DmCmy9) must be submitted upon task completion

**Rewards:**

* All eligible image creators have a chance to split the prize pool of **200,000 LAG** tokens based on the popularity of their images. The more likes your images receive, the greater your reward!
* Prizes:
  * Top 1: 10,000 LAG
  * Top 2-5: 5,000 LAG each
  * Top 6-10: 2,000 LAG each
  * All other participants (rank 11 and beyond) will share the remaining 160,000 LAG pool.

*Note: The ranking will be based on the number of likes received on Creators' tweets showcasing their images.*

## Tutorial

### Table of Content

* [Introduction](#introduction)
* [How to Use LoRA Model to Generate Images](#how-to-use-lora-model-to-generate-images-in-space)
* [How to Upload Images to Multichain.Storage](#how-to-upload-images-to-multichain.storage)
* [How to Share Images on Twitter](#how-to-share-images-on-twitter)

### Introduction

In this tutorial, we'll walk you through the process of completing[ Task 3: Image Creator Task](https://github.com/lagrangedao/community/blob/main/Mars-Testnet/Lagrange-Mars-Testnet-Campaign.md). Your objective is to generate captivating images from the Stable Diffusion Space using the LoRA Model.

What is Stable Diffusion: Stable Diffusion is a state-of-the-art text-to-image model that generates an image from text.

What is Space: Space is a simple way to host ML demo apps on Lagrange.

What is LoRA: LoRA (Low-Rank Adaptation) is a training technique for fine-tuning Stable Diffusion models. and LoRA models are specific versions of the Stable Diffusion model that have undergone fine-tuning.

### How to Use LoRA Model to Generate Images in Space

1\. Visit \[<https://lagrangedao.org/spaces>] and explore Spaces related to "Stable Diffusion" or you can directly access the Stable Diffusion[ Base Space](https://lagrangedao.org/spaces/0x6091b2f5678952cAfbf02755D78973EBff302e11/Stable-Diffusion-Base-LoRA/card) provided by the Official.

<figure><img src="https://lh6.googleusercontent.com/EaetQTnUywtTqlp5cx9pA2NJ_7PzfmhMi74Eg80mboLKNJ3queIa8QbOfn8TTQc7W6CBAAAIloMX3qqNoziX5RJWNGmP1_hLg591cIPxGAms9aJImBxHiLv7bIjUSit2OKbh1yLafSgSpwZPExSg7o0" alt=""><figcaption></figcaption></figure>

2\. Click on the \[App] button to launch the Stable Diffusion Web UI：

<figure><img src="https://lh5.googleusercontent.com/Mkwn8juseNuvMhNNd0lSX7_R4ZBbekFzCou1cQI3mFeRRPRtj42daPGu9Sn2WF4e_TdlQUTjnXlbeHWV0-T5BJr6xin0A9yPfvBJ3yTFmu8X_mA3UY302QzqkKO3_E0tSz0waKROV5-BrRSo5KXv4Og" alt=""><figcaption></figcaption></figure>

3\. Click on \[LoRA] and then several LoRA models will be displayed. Select the one you want to use.

<figure><img src="/files/hcVCM9syLamXyreu58BB" alt=""><figcaption></figcaption></figure>

4\. Each LoRA model has a "Trigger Word", Ensure your prompts include the specific LoRA's trigger word(usually added automatically).

For example, if you choose "KsmRm," its trigger word, \<lora:KsmRm:1>, will be added to the text automatically.

<figure><img src="https://lh4.googleusercontent.com/qa6cEuEE0Oob8yDTs04R2QjVf0Lx4l_uqI0dWsdwlSC5pAGdIUEwsw5hT4r6CArrLOmIZdMFbLD6Sc-1o3xwEKyqDEOpW2rXtm3Pu0OZumW0_KENJhF7X5ZWWinHvA0CveehHUNZQCvXX8-j4scgmd0" alt=""><figcaption></figcaption></figure>

5\. Add the text or description for the image you want to create after the LoRA's trigger words.

<figure><img src="https://lh3.googleusercontent.com/SioHXSAcPng2qBzL5hyuBARMridixgtopjT3TBlDNkD1YaBk8rdY4nr4J83pnCPIWNIEK-pUvX8pxXpZ_OyUOLC5HNF2P8bG8lOjtm4rs3l46wy_FUHuQ3L4galdHEofjgCClfCbv41u6Q7dsOUNJJQ" alt=""><figcaption></figcaption></figure>

Congratulations! An image has been generated from the Stable Diffusion Space using a LoRA model.

\*Note: Feel free to explore not only the Stable Diffusion Base Space but also other Stable Diffusion Spaces that have been enriched by Space Builders. These additional Spaces might offer a wider variety of LoRA models, potentially leading to the generation of even more captivating and attractive images.

### How to Upload Images to Multichain.Storage

1\. Upload your three best images to[ Multichain. Storage](https://www.multichain.storage/) (MCS) using your connected wallet.

2\. Click on \[Bucket Storage] - \[Add Bucket] and then \[Upload] to add your images to MCS.

<figure><img src="https://lh4.googleusercontent.com/uY-EvcswYH4CMOABH8mMW_PkQyOi06TzNkH3aZeUcG6K4qWSw0Mx88bc6T1Bxri03tMyS2ZUyzDjd-sZu4JXrDnXvrAgG5zy2DY7fdi0esej8MQdTgqE-H-ssK_iMeujG8wZrAUgJdruTVGrjF8yBfw" alt=""><figcaption></figcaption></figure>

3\. Obtain the IPFS links of your three images by clicking on the corresponding icon.

<figure><img src="https://lh5.googleusercontent.com/LEsBpE4stMGmKqFSkfpDngua1WczDNxNwIreGjPxnMqpQfdJtCUquhGbHk0rhnJgfrKNDMXCncGeC1CF2RF0GcwPXrhYqTixnGC4z9krmGwgnvcP44iW9KPbVC8J_NCLLraYLWJvY3E9HXvoxiC8Uuc" alt=""><figcaption></figcaption></figure>

\*Note: The IPFS link will be required for the Form submission.

### How to Share Images on Twitter

1\. Click on the share icon and select “Share on Twitter"

<figure><img src="https://lh5.googleusercontent.com/0vG7Iamja2JWfyef0xrN4luwkuC9Ox62e_80y-gT1IZqr0-DIlmZpkw0Jg2ccytun7Icb0au-vlxiIROiZ4JEmcZblDenYmbufVFHf2kHP71PZQZ50MepcvOGvBsmnxzDi8kW2H173hADIyIe6ZVQBE" alt=""><figcaption></figcaption></figure>

2\. Include your three best images in the tweet and remember to tag[ @lagrangedao](https://twitter.com/lagrangedao) and[ @0xfilswan](https://twitter.com/0xfilswan).

<figure><img src="https://lh3.googleusercontent.com/yQr4B-LMVtDQT3jJHI5FuKudAZeA4qp0Nnp_DD7iQ3kCVfMh9Mer9uZVpt4TpBqanG1FNsJMPWp90mB9CvMEiBgJtMcRZCZwY60nPOfjq6nrWYPbx9BaIDp2fj_-9BbOWkSv7BbRS1ylfIMHjeUmTto" alt=""><figcaption></figcaption></figure>

\*Note: The IPFS link will be required for the Form submission.


# Case Study

### Lora Space

### AI Datasets on the Blockchain

### AI Character

*"Lagrange helps us solve xxx by yyyy through zzzz"  from CTO of XXX*

#### Challenge

#### Solution

#### Results

### Music NFT


# FAQ

Question & Answers

#### Q: When is the competition?

A: The Mars Testnet is scheduled to take place on **August 14th, 2023, 23:59 (EST) — September 17th, 2023, 23:59 (EST)**.

### Early Bird Registration FAQs

#### Q: When will I register for the Early Bird form?

A: The Early Bird registration form is open from July 24th, 2023 - August 8th, 2023.

#### Q: What are the Early Bird Benefits?

A: Users will receive the instructions & documentation and assistance. Additionally, there is a higher chance for users to receive rewards.

#### Q: What can we do after registering for the Early Bird form?

A: After registering for the Early Bird program, you should capture the registration evidence to submit it in the Pre-launch Campaign.<br>

### Pre-launch Campaign FAQs

#### Q: What is the Lagrange Pre-launch Campaign?

A: The Lagrange Pre-launch campaign is a series of FilSwan & Lagrange knowledge and community activities. There are several missions launched on Lagrange Zealy opening from August 8th to August 14th.

#### Q: How can access Lagrange Zealy&#x20;

A: Please access to <https://zealy.io/c/lagrangedao/questboard> and enjoy your journey

#### Q: Who is eligible to participate in the Lagrange Pre-Launch Campaign?

A: Everyone is eligible to join the Lagrange Pre-launch Campaign. There are some benefits for the users registered in the Early Bird form & Media Partner.&#x20;

#### Q: Is the pre-launch event free to attend?

A: The pre-launch event will launch on Zealy. It’s a free-of-charge platform so there is no fee needed.

#### Q: Can attendees provide feedback during the pre-launch event?

A: Absolutely! We highly value the feedback of our attendees. There will be dedicated feedback sessions where attendees can share their thoughts, suggestions, and insights.

### Main Event FAQs

#### Q: How can I participate in the testnet?

A:  Feel free to explore [**this page**](https://mars-testnet.lagrangedao.org/) to review tutorials and instructions tailored to the specific tasks that pique your interest. Engage in the campaign activities until the official launch **at 00:00 on August 14th (EST).**

#### Q: What is the Tesnet token? and How can I get the testnet token?

A: The Mumbai Testnet will be used in the Lagrange Tesnet. You can get the test LAG token  via our Discord Channel.

#### Q: Which network are we using in the testnet and what wallet should I use during the testnet?

A: We will use Metamask Wallet. You can switch to Mumbai Network in your Metamask by adding the Mumbai network. Remember to turn on the “show test networks” option from your wallet. &#x20;

#### Q: What should the users do on the Lagrange Mars Testnet?

A: The testnet allows you to perform various types of testing. In terms of experience, you will get 3 tasks belonging to 3 different types of participants:&#x20;

* Computing Providers: All eligible users will share the pool based on their GPU hours, reflecting their active contributions to the Testnet.
* Space Builder (Developers): the users will need to fork a Space from our Base Space and run it successfully. Sharing your forked Space on Twitter and YouTube will not only garner attention but also earn you an incentive.
* Space Users (Everyone): the users will have the opportunity to generate stunning images by Stable-Diffusion-LoRA following a series of weekly themes. Upload your 3 best images on FilSwan Multichain Storage and share them on your Twitter.&#x20;

#### Q: How can I get the testnet token

A: You can get the testnet token via the Discord faucet&#x20;

#### Q: How do I report an issue?

A: Stay connected with our official Twitter and Discord channels if there is any issue.

#### Q: I have many GPUs, will I receive the higher rewards?

A: All eligible Computing Providers will share the reward pool based on your GPU hours, reflecting their active contributions to the Testnet.

#### Q: Where can I find more information about the testnet and project updates?

A: For more information, updates, and official announcements about the testnet and project, please visit the project's website, official social media channels, and community forums.


# API Reference

### Authentication

The Lagrange API uses API token for authentication. Visit your [API Tokens](https://lagrange.computer/personal_center/setting/tokens) page to retrieve the API key you'll use in your requests.


