πŸ€– AI/ML

Modal

A serverless platform for AI/ML workloads

πŸ“– Detailed Explanation

Modal is a serverless cloud platform for AI/ML workloads that lets you run Python code in the cloud with a single decorator line. Founded in 2020, it is designed so that developers can focus on GPU-based computing tasks without managing infrastructure.

Modal's core philosophy is "infrastructure as code": container builds, GPU allocation, and scaling are all defined declaratively within Python code. With cold start optimization, containers start within a few seconds, and it offers a billing model in which you pay only for what you use.

Modal provides integrated GPU/CPU cluster management, container build automation, distributed processing, scheduling, and web endpoint deployment. It is particularly optimized for ML workloads such as LLM inference, image generation, batch processing, and fine-tuning.

In practice, Modal allows you to move from prototype to production with the same code, so it is used for fast ML product development from startups to large enterprises. Compared to AWS and GCP, setup complexity is greatly reduced, and it integrates easily with Hugging Face, vLLM, and others.

Features Modal AWS Lambda GCP Cloud Run
GPU Support A100, H100, A10G Limited L4, A100
Cold Start ~1-3 sec ~1 sec ~5-10 sec
Maximum Execution Time 24 hours 15 minutes 60 minutes
Billing Unit Per second Per ms Per second
Cost per GPU Hour A100: $2.78 N/A A100: $3.67

πŸ’» Code Example

This is an example of building a GPU-based ML inference server using Modal.

# pip install modal
import modal

# μ•± μ •μ˜
app = modal.App("llm-inference")

# GPU 이미지 μ •μ˜ (vLLM + λͺ¨λΈ μΊμ‹œ)
image = modal.Image.debian_slim().pip_install(
    "vllm", "torch", "transformers"
).run_commands(
    "pip install flash-attn --no-build-isolation"
)

# λͺ¨λΈμ„ 영ꡬ λ³Όλ₯¨μ— μΊμ‹œ
volume = modal.Volume.from_name("model-cache", create_if_missing=True)

@app.cls(
    gpu="A100",  # GPU νƒ€μž… μ§€μ •
    image=image,
    volumes={"/models": volume},
    timeout=600,
    container_idle_timeout=300,  # 5λΆ„κ°„ μœ νœ΄μ‹œ μ’…λ£Œ
)
class LLMInference:
    @modal.enter()
    def load_model(self):
        """μ»¨ν…Œμ΄λ„ˆ μ‹œμž‘μ‹œ λͺ¨λΈ λ‘œλ“œ"""
        from vllm import LLM
        self.llm = LLM(
            model="mistralai/Mistral-7B-Instruct-v0.2",
            download_dir="/models",
            max_model_len=4096,
        )

    @modal.method()
    def generate(self, prompt: str, max_tokens: int = 512):
        """ν…μŠ€νŠΈ 생성"""
        from vllm import SamplingParams
        params = SamplingParams(
            max_tokens=max_tokens,
            temperature=0.7,
        )
        outputs = self.llm.generate([prompt], params)
        return outputs[0].outputs[0].text

    @modal.web_endpoint(method="POST")
    def api(self, request: dict):
        """μ›Ή API μ—”λ“œν¬μΈνŠΈ"""
        prompt = request.get("prompt", "")
        result = self.generate(prompt)
        return {"response": result}


# 배치 처리 ν•¨μˆ˜
@app.function(gpu="A10G", image=image, timeout=3600)
def batch_inference(prompts: list[str]):
    """λŒ€λŸ‰ ν”„λ‘¬ν”„νŠΈ 배치 처리"""
    from vllm import LLM, SamplingParams

    llm = LLM(model="mistralai/Mistral-7B-Instruct-v0.2")
    params = SamplingParams(max_tokens=256)

    outputs = llm.generate(prompts, params)
    return [o.outputs[0].text for o in outputs]


# μŠ€μΌ€μ€„ μž‘μ—… (맀일 μžμ •)
@app.function(schedule=modal.Cron("0 0 * * *"))
def daily_task():
    """일일 배치 μž‘μ—…"""
    print("Daily batch job running...")


# λ‘œμ»¬μ—μ„œ μ‹€ν–‰
if __name__ == "__main__":
    with app.run():
        inference = LLMInference()
        result = inference.generate.remote("Explain quantum computing:")
        print(result)

Deploy and run from the terminal:

# Modal CLI μ„€μ •
modal setup

# 둜컬 ν…ŒμŠ€νŠΈ μ‹€ν–‰
modal run app.py

# ν”„λ‘œλ•μ…˜ 배포
modal deploy app.py

# 배치 처리 λ§΅ (병렬 μ‹€ν–‰)
modal run app.py::batch_inference --input prompts.json

# μ„œλ²„ 둜그 확인
modal app logs llm-inference

πŸ—£οΈ Example Conversations in Practice

πŸ’Ό In a Meeting

"Managing GPU servers is a burden, but with Modal you can run an LLM on an A100 without worrying about infrastructure. Deployment is just a single modal deploy line, and since you are billed only for the time you use, costs are predictable too."

🎀 In an Interview

"Modal is a serverless ML platform that defines GPU containers with Python decorators. Cold starts are fast, and if you cache models in a volume, you can get fast responses even after a restart. You can think of it as the GPU version of AWS Lambda."

πŸ”§ In a Technical Discussion

"The advantage of Modal is that you can optimize costs while keeping warm containers with container_idle_timeout. And if you process thousands of tasks in parallel with .map(), you can do batch processing at a similar cost to EC2 Spot, without the management burden."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

❌ Wrong approach: If you run on Modal by default without specifying a GPU type, only the CPU is used.

βœ… Right approach: Explicitly specify the GPU type, such as @app.function(gpu="A100") or gpu="A10G".

❌ Wrong approach: If you download a large model on every request, cold starts take several minutes.

βœ… Right approach: Cache the model in a Volume and load it only once in @modal.enter(). Baking the model in when building the image is also an option.

❌ Wrong approach: If you set the web endpoint timeout too short, generation is interrupted midway through an LLM response.

βœ… Right approach: Set timeout=300 or higher for LLM inference, and if you need streaming, return a generator from @modal.web_endpoint().

πŸ”— Related Terms

πŸ“š Learn More