<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hazqeel Afyq on Medium]]></title>
        <description><![CDATA[Stories by Hazqeel Afyq on Medium]]></description>
        <link>https://medium.com/@hazqeelafyq09?source=rss-c4e459d69bfe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*S_JpM2sTYzkP6ANx</url>
            <title>Stories by Hazqeel Afyq on Medium</title>
            <link>https://medium.com/@hazqeelafyq09?source=rss-c4e459d69bfe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 15:03:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hazqeelafyq09/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Self-Host Hatchet + Full-Stack App on AWS]]></title>
            <link>https://medium.com/@hazqeelafyq09/self-host-hatchet-full-stack-app-on-aws-b7b9c3a2adc8?source=rss-c4e459d69bfe------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7b9c3a2adc8</guid>
            <dc:creator><![CDATA[Hazqeel Afyq]]></dc:creator>
            <pubDate>Tue, 09 Dec 2025 06:36:17 GMT</pubDate>
            <atom:updated>2025-12-09T06:47:28.650Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XAqa-VpESTYxDNfb2vguRg.png" /></figure><h3>What is Hatchet</h3><p>Hatchet is this open-source task orchestrator that runs on top of Postgres. It acts like a durable task queue for background jobs and workflows. It handles scheduling, fault tolerance, observability, and putting together multiple tasks in workflows you set up. It’s built for things like data pipelines and AI agents where you need stuff to run reliably without constant watching. This <a href="https://jack-vanlightly.com/blog/2025/11/24/demystifying-determinism-in-durable-execution">blog</a> is a good read to understand about determinism in durable execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L8xU5Tq9pJoROYOp.png" /></figure><p>The image is from Hatchet where you can read more about their architecture <a href="https://docs.hatchet.run/home/architecture">here</a>.</p><h3>Why We Use Hatchet</h3><p>We use Hatchet because it fixes a bunch of headaches without getting too complicated. Other task orchestrators need tons of extra services like RabbitMQ or Kafka, but with Hatchet, we can skip RabbitMQ and just use Postgres for the message queue if we’re under about 100 requests a second. That means less stuff to handle, deploy, and fix.</p><p>At <a href="https://cynco.io/">Cynco</a>, we make multiple AI calls and had to hack workarounds to wait for responses or retry on rate limits and connection problems. Hatchet handles this with automatic retry policies for those failures, durable execution that picks up right where it left off without losing anything, and fault-tolerant queuing that takes care of waiting and retries automatically, no more custom hacks.</p><p>We also process a lot of data from many users at once, but want fairness, so we do group round-robin queues. Our old Golang queue was just FIFO, so the 100th user waited for the first 99 to finish before seeing any progress. Hatchet helps with fair queuing strategies like deterministic round-robin using group keys for multi-tenancy, so tasks from different users get mixed in fairly, with concurrency and rate limits per tenant to stop anyone from hogging it all.</p><p>Plus, our old in-RAM queue wasn’t durable and poofed on crashes. Hatchet fixes this with Postgres-backed storage for all task states, making everything persistent and easy to recover even if things crash.</p><p>Hatchet has SDKs for Golang, TypeScript, and Python, making the language choice more robust because some task orchestrators only cater to one or two languages like Prefect which only caters to Python.</p><h3>When to Use Hatchet</h3><p>Use Hatchet when you have background tasks that need to scale reliably, especially for AI apps, data processing, or anything where failures, retries, and fairness are key. It’s great for long-running ops like AI API calls that hit rate limits or timeouts, multi-user setups needing fair scheduling to keep one user from blocking others, or when you want durability without a huge setup. At <a href="https://cynco.io/">Cynco</a>, we grabbed it for our AI workflows to drop the hacks around waiting and retrying, and to get that group round-robin for user fairness. Basically, pull it in when your simple queue isn’t cutting it on reliability or scale, but you don’t want to deal with complex tools like Temporal or Airflow that need a bunch of dependencies. If your throughput is low, under 100 a second, the Postgres-only mode keeps it simple. Scale up with RabbitMQ later if you need.</p><h3>The Tutorial</h3><p>For this tutorial, we will stick with:</p><ol><li>React Router v7 (RRv7) as the frontend.</li><li>Golang as the backend.</li><li>Hatchet as the task orchestrator.</li><li>Docker for containerization.</li><li>AWS for hosting.</li><li>Tailscale for secure networking.</li></ol><p>You can follow the official docs to set up RRv7, Golang, Docker, and Tailscale. If I tried to explain every little detail here, it would turn into a novel. Nobody wants that.<br>Next up, install the Hatchet SDK for Golang since we are hooking it up with our backend. Just run</p><pre>go get -u github.com/hatchet-dev/hatchet/sdks/go@latest<br>go mod tidy</pre><p>in your Golang project. Make sure you have Go installed and your GOPATH set up right.</p><p>Now, get Hatchet Lite running locally and follow their <a href="https://docs.hatchet.run/home/setup">Golang quickstart tutorial</a>. It will show you how to define workflows, steps, and workers. Once you have tested it and confirmed everything works, like triggering a simple workflow and seeing it execute, we can wrap the Golang part into an API. Expose endpoints in your Golang server using the simple net/http package or any framework you like so that RRv7 can call them to kick off Hatchet workflows. For example, create a /trigger-workflow endpoint that runs a workflow based on incoming JSON from the frontend. The workflow and worker should be initialized before you call the endpoint.</p><p>After confirming the local setup works, let us containerize everything with Docker Compose. Set up one Compose file for your RRv7 frontend and Golang backend. For example, here is a basic docker-compose.yml for the app side (make sure you have Dockerfiles in ./frontend and ./backend directories):</p><pre>version: ‘3.8’<br>services:<br>  frontend:<br>    build: ./frontend<br>    ports:<br>      - ‘3000:3000’<br>    environment:<br>      - NODE_ENV=production<br>    depends_on:<br>      - backend<br><br>  backend:<br>    build: ./backend<br>    ports:<br>      - ‘8080:8080’<br>    environment:<br>      - HATCHET_SERVER_URL=${HATCHET_SERVER_URL}<br>      - HATCHET_CLIENT_TOKEN=${HATCHET_CLIENT_TOKEN}<br>    volumes:<br>      - .:/app</pre><p>Tweak paths and env vars as needed, but this should be good enough. We will inject HATCHET_CLIENT_TOKEN and HATCHET_SERVER_URL (e.g., <a href="http://your-hatchet-url:7077)">http://your-hatchet-url:7077)</a> via GitHub secrets during deployment into a .env file, so no hardcoding or placeholders here. This way, the Compose file can pull them dynamically when you run docker compose up — env-file .env.</p><p>For the Hatchet side, use their <a href="https://docs.hatchet.run/self-hosting/docker-compose">official Docker Compose</a> as a base. It includes Postgres, migrations, engine, and dashboard. To stick with just Postgres and ditch RabbitMQ, remove the rabbitmq service, the hatchet_rabbitmq_data and hatchet_rabbitmq.conf volumes, and any RabbitMQ-related depends_on or environment variables. Here is the full customized version with SERVER_MSGQUEUE_KIND set to postgres, plus some tweaks like bumped shm_size for Postgres stability:</p><pre>version: “3.8”<br>services:<br>  postgres:<br>    image: postgres:15.6<br>    shm_size: 1g<br>    command: postgres -c ‘max_connections=1000’<br>    restart: always<br>    hostname: “postgres”<br>    environment:<br>      - POSTGRES_USER=hatchet<br>      - POSTGRES_PASSWORD=${HATCHET_POSTGRES_PASSWORD}<br>      - POSTGRES_DB=hatchet<br>    ports:<br>      - “5435:5432”<br>    volumes:<br>      - hatchet_postgres_data:/var/lib/postgresql/data<br>    healthcheck:<br>      test: [”CMD-SHELL”, “pg_isready -d hatchet -U hatchet”]<br>      interval: 10s<br>      timeout: 10s<br>      retries: 5<br>      start_period: 10s<br>  migration:<br>    image: ghcr.io/hatchet-dev/hatchet/hatchet-migrate:latest<br>    command: /hatchet/hatchet-migrate<br>    environment:<br>      DATABASE_URL: “postgres://hatchet:${HATCHET_POSTGRES_PASSWORD}@postgres:5432/hatchet”<br>    depends_on:<br>      postgres:<br>        condition: service_healthy<br>  setup-config:<br>    image: ghcr.io/hatchet-dev/hatchet/hatchet-admin:latest<br>    command: /hatchet/hatchet-admin quickstart --skip certs --generated-config-dir /hatchet/config --overwrite=false<br>    environment:<br>      DATABASE_URL: “postgres://hatchet:${HATCHET_POSTGRES_PASSWORD}@postgres:5432/hatchet”<br>      ADMIN_EMAIL: ${HATCHET_ADMIN_EMAIL}<br>      ADMIN_PASSWORD: ${HATCHET_ADMIN_PASSWORD}<br>      ADMIN_NAME: YOUR-ADMIN-NAME<br>      SERVER_AUTH_COOKIE_DOMAIN: {localhost-or-yourec2ipv4privateaddress}:8080<br>      SERVER_AUTH_COOKIE_INSECURE: “t”<br>      SERVER_GRPC_BIND_ADDRESS: “0.0.0.0”<br>      SERVER_GRPC_INSECURE: “t”<br>      SERVER_GRPC_BROADCAST_ADDRESS: {localhost-or-yourec2ipv4privateaddress}:7077<br>      SERVER_DEFAULT_ENGINE_VERSION: “V1”<br>      SERVER_INTERNAL_CLIENT_INTERNAL_GRPC_BROADCAST_ADDRESS: hatchet-engine:7070<br>      SERVER_MSGQUEUE_KIND: postgres<br>    volumes:<br>      - hatchet_certs:/hatchet/certs<br>      - hatchet_config:/hatchet/config<br>    depends_on:<br>      migration:<br>        condition: service_completed_successfully<br>      postgres:<br>        condition: service_healthy<br>  hatchet-engine:<br>    image: ghcr.io/hatchet-dev/hatchet/hatchet-engine:latest<br>    command: /hatchet/hatchet-engine --config /hatchet/config<br>    restart: on-failure<br>    depends_on:<br>      setup-config:<br>        condition: service_completed_successfully<br>      migration:<br>        condition: service_completed_successfully<br>    ports:<br>      - “7077:7070”<br>    environment:<br>      DATABASE_URL: “postgres://hatchet:${HATCHET_POSTGRES_PASSWORD}@postgres:5432/hatchet”<br>      SERVER_GRPC_BIND_ADDRESS: “0.0.0.0”<br>      SERVER_GRPC_INSECURE: “t”<br>    volumes:<br>      - hatchet_certs:/hatchet/certs<br>      - hatchet_config:/hatchet/config<br>  hatchet-dashboard:<br>    image: ghcr.io/hatchet-dev/hatchet/hatchet-dashboard:latest<br>    command: sh ./entrypoint.sh --config /hatchet/config<br>    ports:<br>      - 8080:80<br>    restart: on-failure<br>    depends_on:<br>      setup-config:<br>        condition: service_completed_successfully<br>      migration:<br>        condition: service_completed_successfully<br>    environment:<br>      DATABASE_URL: “postgres://hatchet:${HATCHET_POSTGRES_PASSWORD}@postgres:5432/hatchet”<br>    volumes:<br>      - hatchet_certs:/hatchet/certs<br>      - hatchet_config:/hatchet/config<br><br>volumes:<br>  hatchet_postgres_data:<br>  hatchet_config:<br>  hatchet_certs:</pre><p>Replace placeholders like {localhost-or-yourec2ipv4privateaddress} with your actual localhost or the private IPv4 address of your Hatchet EC2 instance for production. Remember, we need to add HATCHET_POSTGRES_PASSWORD, HATCHET_ADMIN_EMAIL, and HATCHET_ADMIN_PASSWORD into our Github Actions Secrets so that we can use it or if you want to run on local, you need to add those in .env. This will make sure we are using our own admin email and admin password, not the default that Hatchet set.</p><p>Now, for deployment, we will use CI/CD to push to AWS EC2. Spin up two EC2 instances first (t3.micro free tier if you have credits left). Put them in the same VPC and subnet for easy private networking. Configure the security groups properly. Create a shared security group (say, sg-hatchet-app) and attach it to both instances. This allows self-referential rules for inter-instance communication. Start with these inbound rules on the shared SG:</p><ul><li>Type: SSH, Protocol: TCP, Port: 22, Source: Your IP address only (e.g., 203.0.113.0/32) for initial setup.</li><li>Type: HTTP, Protocol: TCP, Port: 80, Source: 0.0.0.0/0 (if using NGINX publicly later; otherwise, restrict to your IP or Tailscale subnet).</li><li>Type: HTTPS, Protocol: TCP, Port: 443, Source: 0.0.0.0/0 (same as above, for secure access).</li><li>Type: Custom TCP, Protocol: TCP, Port: 3000, Source: Tailscale subnet (100.64.0.0/10) or your IP (for RRv7 if exposing directly; skip if behind NGINX).</li><li>Type: Custom TCP, Protocol: TCP, Port: 8080, Source: sg-hatchet-app (self) or the app EC2’s private IP (for Hatchet dashboard access, internally from app EC2 or via Tailscale).</li><li>Type: Custom TCP, Protocol: TCP, Port: 7077, Source: sg-hatchet-app (self) or the app EC2’s private IP (for Hatchet gRPC engine, so the Golang backend can connect to Hatchet).</li><li>Type: Custom TCP, Protocol: TCP, Port: 5435, Source: sg-hatchet-app (self) if exposing Postgres externally (usually not needed, as it is internal to Hatchet containers).</li><li>Type: All ICMP — IPv4, Protocol: ICMP, Port: All, Source: The VPC’s CIDR block (e.g., 10.0.0.0/32) or sg-hatchet-app (self). This allows ping tests between instances within the VPC for connectivity checks.</li></ul><p>For outbound rules, allow all traffic (default). This setup keeps things locked down: public access only where needed, internal comms via self-SG or private IPs.<br>SSH into both EC2s (using your key pair) and install Tailscale like before. Once Tailscale is running, you can safely delete the public SSH inbound rule. Now you will SSH via Tailscale IPs (e.g., ssh <a href="/service/mailto:user@100.x.x.x">user@100.x.x.x</a>). This keeps things locked down.<br>To access your web app properly later, set up NGINX as a reverse proxy on the app EC2 (point it to your RRv7 port, say 3000, and Golang on 8080). If you have a domain, use Cloudflare DNS to point to the EC2’s public IP (or Elastic IP for stability), and enable HTTPS with Let’s Encrypt.</p><p>For CI/CD, we will use GitHub Actions. For both Hatchet and the app, go with workflow_dispatch so it does not auto-deploy on every push to main. We will trigger them manually. Deploying via SSH works fine for small-scale stuff since it is straightforward and you can lock it down with Tailscale or restricted security groups. But it is not the absolute best practice for production or bigger teams, because it involves managing SSH keys (which can be a security hassle) and potentially exposing port 22. This approach will be used only during this tutorial for simplicity. In real-world scenarios, consider alternatives like AWS CodeDeploy (integrates directly with GitHub Actions for rolling deploys without SSH) or AWS Systems Manager (SSM) for session-based access, they are often recommended for better security and scalability, as they avoid long-lived keys and use IAM roles with OIDC federation.</p><p>To get your ARN secret for the workflows below, we’re talking about an IAM role ARN for secure AWS access from GitHub Actions without long-lived keys — better security, less headache. Just head to the GitHub Docs for setting up the OIDC <a href="https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-aws">here</a>. Then, you can add it to your GitHub Actions secrets, but you can just hardcode it too cause knowing an ARN by itself doesn’t let someone access or mess with your stuff</p><p>Before setting up the workflows, you need to configure these secrets in your GitHub repo settings &gt; Secrets and Variables &gt; Actions (grab credentials from AWS IAM if using AWS CLI, or SSH keys for direct deploy). List them all here:</p><ul><li>AWS_ACCESS_KEY_ID # Optional if not using ECR; skip if pure SSH</li><li>AWS_SECRET_ACCESS_KEY # Same as above</li><li>EC2_HOST (your EC2 public IP or Tailscale IP for the app instance)</li><li>EC2_USER (e.g., ubuntu)</li><li>SSH_PRIVATE_KEY (your PEM key for SSH)</li><li>HATCHET_EC2_HOST (separate for Hatchet EC2, if different from EC2_HOST)</li><li>HATCHET_CLIENT_TOKEN (add this after getting it from the dashboard; it’s stored here as a secret for secure injection)</li><li>HATCHET_SERVER_URL (e.g., <a href="http://your-hatchet-ec2-private-ip:7077;">http://your-hatchet-ec2-private-ip:7077;</a> set this based on your Hatchet EC2 setup)</li><li>HATCHET_POSTGRES_PASSWORD (secure password for Postgres in Hatchet)</li><li>HATCHET_ADMIN_EMAIL (admin email for Hatchet login)</li><li>HATCHET_ADMIN_PASSWORD (secure password for Hatchet admin)</li><li>DOCKER_USERNAME (for pushing images to Docker Hub)</li><li>DOCKER_PASSWORD (for Docker Hub login)</li><li>AWS_REGION (your AWS region, like us-east-1)</li><li>AWS_INSTANCE_SG_ID (the ID of your shared security group for temp whitelisting)</li><li>AWS_ROLE_ARN (the full ARN of the IAM role you’ll create for GitHub Actions to assume; grab it from the AWS console after following the link above)</li></ul><p>Here is an example CI/CD workflow for RRv7 and Golang (save as .github/workflows/deploy-app.yml):</p><pre>name: Deploy App to EC2<br><br>on:<br>  workflow_dispatch:<br><br>jobs:<br>  build-push-deploy:<br>    name: Build, Push and Deploy App<br>    runs-on: ubuntu-latest<br>    permissions:<br>      id-token: write<br>      contents: read<br><br>    env:<br>      AWS_REGION: ${{ secrets.AWS_REGION }}<br>      EC2_HOST: ${{ secrets.EC2_HOST }}<br>      AWS_INSTANCE_SG_ID: ${{ secrets.AWS_INSTANCE_SG_ID }}<br><br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v4<br><br>      - name: Set up Docker Buildx<br>        uses: docker/setup-buildx-action@v3<br><br>      - name: Log in to Docker Hub<br>        uses: docker/login-action@v3<br>        with:<br>          username: ${{ secrets.DOCKER_USERNAME }}<br>          password: ${{ secrets.DOCKER_PASSWORD }}<br><br>      - name: Build and push Frontend Docker image<br>        uses: docker/build-push-action@v5<br>        with:<br>          context: ./frontend<br>          push: true<br>          tags: ${{ secrets.DOCKER_USERNAME }}/hatchet-frontend:latest<br><br>      - name: Build and push Backend Docker image<br>        uses: docker/build-push-action@v5<br>        with:<br>          context: ./backend<br>          push: true<br>          tags: ${{ secrets.DOCKER_USERNAME }}/hatchet-backend:latest<br><br>      - name: Configure AWS credentials<br>        uses: aws-actions/configure-aws-credentials@v4<br>        with:<br>          role-to-assume: ${{ env.AWS_ROLE_ARN }}<br>          aws-region: ${{ env.AWS_REGION }}<br><br>      - name: Get runner IP address<br>        id: ip<br>        uses: haythem/public-ip@v1.3<br><br>      - name: Whitelist runner IP address for SSH<br>        run: |<br>          aws ec2 authorize-security-group-ingress \<br>            --group-id $AWS_INSTANCE_SG_ID \<br>            --protocol tcp \<br>            --port 22 \<br>            --cidr ${{ steps.ip.outputs.ipv4 }}/32<br>        continue-on-error: true<br><br>      - name: Create .ssh directory and SSH key file<br>        run: |<br>          mkdir -p /home/runner/.ssh<br>          echo “${{ secrets.SSH_PRIVATE_KEY }}” &gt; /home/runner/.ssh/ec2_key<br>          chmod 600 /home/runner/.ssh/ec2_key<br><br>      - name: Transfer docker-compose.yml to EC2<br>        run: |<br>          scp -o StrictHostKeyChecking=no -i /home/runner/.ssh/ec2_key \<br>            ./docker-compose.yml ubuntu@${{ env.EC2_HOST }}:/home/ubuntu/docker-compose.yml<br><br>      - name: Clean up disk space on EC2<br>        uses: appleboy/ssh-action@v1.0.3<br>        with:<br>          host: ${{ env.EC2_HOST }}<br>          username: ${{ secrets.EC2_USER }}<br>          key: ${{ secrets.SSH_PRIVATE_KEY }}<br>          script: |<br>            echo “Cleaning up Docker resources...”<br>            sudo docker system prune -a -f<br>            sudo docker volume prune -f<br>            echo “Cleaning package caches...”<br>            sudo apt-get clean<br>            echo “Available disk space after cleanup:”<br>            df -h /<br><br>      - name: Deploy to EC2<br>        uses: appleboy/ssh-action@v1.0.3<br>        with:<br>          host: ${{ env.EC2_HOST }}<br>          username: ${{ secrets.EC2_USER }}<br>          key: ${{ secrets.SSH_PRIVATE_KEY }}<br>          command_timeout: 20m<br>          script: |<br>            mkdir -p /home/ubuntu/app<br>            mv /home/ubuntu/docker-compose.yml /home/ubuntu/app/docker-compose.yml<br>            cd /home/ubuntu/app<br>            echo “HATCHET_CLIENT_TOKEN=${{ secrets.HATCHET_CLIENT_TOKEN }}” &gt; .env<br>            echo “HATCHET_SERVER_URL=${{ secrets.HATCHET_SERVER_URL }}” &gt;&gt; .env<br>            export COMPOSE_HTTP_TIMEOUT=1200<br>            sudo docker compose --env-file .env pull<br>            sudo docker compose --env-file .env up -d --remove-orphans<br><br>      - name: Revoke runner IP address from SSH access<br>        if: always()<br>        run: |<br>          aws ec2 revoke-security-group-ingress \<br>            --group-id $AWS_INSTANCE_SG_ID \<br>            --protocol tcp \<br>            --port 22 \<br>            --cidr ${{ steps.ip.outputs.ipv4 }}/32</pre><p>Here is the example CI/CD for Hatchet (save as .github/workflows/deploy-hatchet.yml). Notice workflow_dispatch for manual runs:</p><pre>name: Deploy Hatchet to EC2<br><br>on:<br>  workflow_dispatch:<br><br>jobs:<br>  deploy-hatchet:<br>    name: Deploy Hatchet<br>    runs-on: ubuntu-latest<br>    permissions:<br>      id-token: write<br>      contents: read<br><br>    env:<br>      AWS_REGION: ${{ secrets.AWS_REGION }}<br>      HATCHET_EC2_HOST: ${{ secrets.HATCHET_EC2_HOST }}<br>      AWS_INSTANCE_SG_ID: ${{ secrets.AWS_INSTANCE_SG_ID }}<br><br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v4<br><br>      - name: Configure AWS credentials<br>        uses: aws-actions/configure-aws-credentials@v4<br>        with:<br>          role-to-assume: ${{ env.AWS_ROLE_ARN }}<br>          aws-region: ${{ env.AWS_REGION }}<br><br>      - name: Get runner IP address<br>        id: ip<br>        uses: haythem/public-ip@v1.3<br><br>      - name: Whitelist runner IP address for SSH<br>        run: |<br>          aws ec2 authorize-security-group-ingress \<br>            --group-id $AWS_INSTANCE_SG_ID \<br>            --protocol tcp \<br>            --port 22 \<br>            --cidr ${{ steps.ip.outputs.ipv4 }}/32<br>        continue-on-error: true<br><br>      - name: Create .ssh directory and SSH key file<br>        run: |<br>          mkdir -p /home/runner/.ssh<br>          echo “${{ secrets.SSH_PRIVATE_KEY }}” &gt; /home/runner/.ssh/ec2_key<br>          chmod 600 /home/runner/.ssh/ec2_key<br><br>      - name: Transfer Hatchet docker-compose to EC2<br>        run: |<br>          scp -o StrictHostKeyChecking=no -i /home/runner/.ssh/ec2_key \<br>            ./hatchet-docker-compose.yml ubuntu@${{ env.HATCHET_EC2_HOST }}:/home/ubuntu/hatchet-docker-compose.yml<br><br>      - name: Clean up disk space on Hatchet EC2<br>        uses: appleboy/ssh-action@v1.0.3<br>        with:<br>          host: ${{ env.HATCHET_EC2_HOST }}<br>          username: ${{ secrets.EC2_USER }}<br>          key: ${{ secrets.SSH_PRIVATE_KEY }}<br>          script: |<br>            echo “Cleaning up Docker resources...”<br>            sudo docker system prune -a -f<br>            sudo docker volume prune -f<br>            echo “Cleaning package caches...”<br>            sudo apt-get clean<br>            echo “Available disk space after cleanup:”<br>            df -h /<br><br>      - name: Deploy Hatchet<br>        uses: appleboy/ssh-action@v1.0.3<br>        with:<br>          host: ${{ env.HATCHET_EC2_HOST }}<br>          username: ${{ secrets.EC2_USER }}<br>          key: ${{ secrets.SSH_PRIVATE_KEY }}<br>          command_timeout: 20m<br>          script: |<br>            mkdir -p /home/ubuntu/hatchet<br>            mv /home/ubuntu/hatchet-docker-compose.yml /home/ubuntu/hatchet/docker-compose.yml<br>            cd /home/ubuntu/hatchet<br>            echo “HATCHET_POSTGRES_PASSWORD=${{ secrets.HATCHET_POSTGRES_PASSWORD }}” &gt; .env<br>            echo “HATCHET_ADMIN_EMAIL=${{ secrets.HATCHET_ADMIN_EMAIL }}” &gt;&gt; .env<br>            echo “HATCHET_ADMIN_PASSWORD=${{ secrets.HATCHET_ADMIN_PASSWORD }}” &gt;&gt; .env<br>            chmod 600 .env<br>            sudo chown -R ubuntu:ubuntu /home/ubuntu/hatchet<br>            sudo docker compose --env-file .env pull<br>            sudo docker compose --env-file .env down<br>            sudo docker compose --env-file .env up -d --remove-orphans<br>            echo “Waiting for Hatchet services to start...”<br>            sleep 15<br>            sudo docker compose ps<br>            echo “=== Hatchet Deployment Logs ===”<br>            sudo docker compose logs --tail=50<br><br>      - name: Verify Hatchet deployment<br>        uses: appleboy/ssh-action@v1.0.3<br>        with:<br>          host: ${{ env.HATCHET_EC2_HOST }}<br>          username: ${{ secrets.EC2_USER }}<br>          key: ${{ secrets.SSH_PRIVATE_KEY }}<br>          script: |<br>            cd /home/ubuntu/hatchet<br>            echo “=== Service Health Check ===”<br>            sudo docker compose ps<br>            if sudo docker compose exec -T postgres pg_isready -U hatchet; then<br>              echo “PostgreSQL is healthy”<br>            else<br>              echo “PostgreSQL is not ready”<br>              exit 1<br>            fi<br>            if sudo docker compose ps hatchet-engine | grep -q “Up”; then<br>              echo “Hatchet Engine is running”<br>            else<br>              echo “Hatchet Engine is not running”<br>              exit 1<br>            fi<br>            if sudo docker compose ps hatchet-dashboard | grep -q “Up”; then<br>              echo “Hatchet Dashboard is running”<br>            else<br>              echo “Hatchet Dashboard is not running”<br>              exit 1<br>            fi<br>            echo “=== Hatchet Deployment Successful ===”<br>            echo “Dashboard URL: http://${{ env.HATCHET_EC2_HOST }}:8080”<br>            echo “Engine gRPC: ${{ env.HATCHET_EC2_HOST }}:7077”<br>            echo “PostgreSQL: ${{ env.HATCHET_EC2_HOST }}:5435”<br><br>      - name: Revoke runner IP address from SSH access<br>        if: always()<br>        run: |<br>          aws ec2 revoke-security-group-ingress \<br>            --group-id $AWS_INSTANCE_SG_ID \<br>            --protocol tcp \<br>            --port 22 \<br>            --cidr ${{ steps.ip.outputs.ipv4 }}/32</pre><p>Now, push your code to main first, but that will not trigger any deploys since both workflows are manual. Before triggering deployments, head to AWS console &gt; EC2 &gt; Security Groups, and confirm or add the inbound rules as detailed above so the app EC2 can talk to Hatchet EC2 securely. Since they are in the same VPC, this keeps it internal. No public exposure.</p><p>SSH into the app EC2 (via Tailscale), then try pinging the Hatchet EC2 using its Tailscale name (e.g., ping hatchet-machine) to confirm connectivity. Then ping using the private IPv4 address (find it in AWS console) to double-check VPC networking. If those pings work, you know the basic networking is solid before apps go live.</p><p>While you’re SSH’d in, you’ll also need to set up Docker and Docker Compose on both instances since our deployments rely on them. On each EC2 (as ubuntu or your user), run these commands one by one to install Docker and Compose:</p><pre>sudo apt update<br>sudo apt install -y docker.io<br>sudo systemctl start docker<br>sudo systemctl enable docker<br>sudo usermod -aG docker $USER<br>sudo mkdir -p /usr/local/lib/docker/cli-plugins<br>sudo curl -SL https://github.com/docker/compose/releases/latest/download/docker-compose-linux-$(uname -m) -o /usr/local/lib/docker/cli-plugins/docker-compose<br>sudo chmod +x /usr/local/lib/docker/cli-plugins/docker-compose</pre><p>Log out and back in for the group change to kick in, then test with docker --version and docker compose --version. If you hit any snags like permission issues, double-check the usermod step or reboot the instance. This keeps things containerized without extra hassle.</p><p>Start by manually triggering the Hatchet deployment: head to your GitHub repo’s Actions tab, find the deploy-hatchet workflow, and hit “Run workflow” to get Hatchet up on its EC2. Once that is done, access the Hatchet dashboard on {tailscale-magic-link-2}:8080 (default dashboard port. Tweak if you changed it). Log in with the credentials you set via HATCHET_ADMIN_EMAIL and HATCHET_ADMIN_PASSWORD, go to Settings &gt; API Tokens &gt; Create. Copy the key, then add it to your GitHub secrets as HATCHET_CLIENT_TOKEN. Now head back to the Actions tab and manually trigger the deploy-app workflow. That will deploy the RRv7 and Golang Docker Compose to the app EC2 with the real token injected via the secret in the workflow (like in the script above, appending to .env or passing directly).</p><p>After deployment, access the web app locally via {tailscale-magic-link}:3000 (or whatever port your RRv7 exposes). If all that checks out, fire up your web app, hit a button in RRv7 to call the Golang API, which triggers a Hatchet workflow, processes it, and bounces results back to Golang then RRv7. Watch the Hatchet dashboard for logs to debug.</p><p>That is it. You have got a solid, secure setup. Remember to monitor logs, rotate keys regularly, and scale EC2 if things get busy.</p><p>I just wrote this off the top of my head, so there might be some stuff left out. If you experience any errors, please comment so we can make this better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7b9c3a2adc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Face Liveness Detection with Pretrained ViT Base: A Step-by-Step Tutorial]]></title>
            <link>https://medium.com/@hazqeelafyq09/optimizing-face-liveness-detection-with-pretrained-vit-base-a-step-by-step-tutorial-8b9c8794ab7d?source=rss-c4e459d69bfe------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b9c8794ab7d</guid>
            <category><![CDATA[face-liveness]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Hazqeel Afyq]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 16:05:26 GMT</pubDate>
            <atom:updated>2024-02-27T07:45:12.236Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2TpmITdeF2hmpQR7" /></figure><p>This is Part 2 of our experimentation using PyTorch for face liveness. You can read Part 1 <a href="https://medium.com/@hazqeelafyq09/pytorch-and-face-liveness-detection-a-comprehensive-guide-007b926bb222">here</a>.</p><p>In this article, we will fine-tune a pre-trained ViT Base model with the specified dataset. If you have not yet downloaded this dataset, please refer to <a href="https://medium.com/@hazqeelafyq09/pytorch-and-face-liveness-detection-a-comprehensive-guide-007b926bb222">Part 1</a> of our series to access it.</p><h4>Distillation</h4><p>Distillation fundamentally involves transferring knowledge from a larger model to a smaller one, enabling the smaller model to achieve performance comparable to that of the larger model. To accomplish distillation, both a teacher model and a student model are required.</p><p>There are several methods for performing distillation. One approach is to use Kullback-Leibler divergence loss to compare the logits values between the teacher and student model outputs. This loss is then combined with the task-specific loss. Additionally, feature space distillation can be employed, where comparison is made between layers — typically the one preceding the head layer or any preferred layer, depending on the distillation method.</p><p>In this article, we focus on feature space distillation utilizing a projector layer. The projector layer is applied to the feature space of the student model to align its features with those of the teacher model. We then calculate the LogSum distance between these features, as outlined in the paper mentioned in Part 1. Finally, this distance is added to the task-specific loss to derive the total loss.</p><h4>Prepare Dataset</h4><p>After downloading the dataset, unzip it and place the image folder in the same directory as your code. Name this folder ‘Detectedface’. Inside it, there will be two subfolders: ‘ClientFace’ and ‘ImposterFace’. Each folder contains 15 subfolders, each representing a different person. Note that the ‘ImposterFace’ folder skips number 13. For consistency, rename the subsequent folders to 13, 14, and 15. We will copy the images to new folders instead of transferring them, as we will use the ‘Detectedface’ folder for Part 3 of our project.</p><p>Next, create a new folder named ‘face_train’. Inside it, create two subfolders named ‘fake’ and ‘real’. Copy all the odd-numbered folders from ‘ClientFace’ to the ‘real’ folder, and do the same with ‘ImposterFace’, copying them to the ‘fake’ folder.</p><p>Then, create another folder named ‘face_val’. Within this, again create two subfolders named ‘fake’ and ‘real’. Copy the folders numbered 0002, 0004, and 0006 from ‘ClientFace’ to the ‘real’ folder, and the same numbered folders from ‘ImposterFace’ to the ‘fake’ folder.</p><p>Finally, create a folder named ‘face_test’. In this folder, create two subfolders named ‘fake’ and ‘real’. Copy the folders numbered 0008, 0010, 0012, and 0014 from ‘ClientFace’ to the ‘real’ folder, and the same numbered folders from ‘ImposterFace’ to the ‘fake’ folder.</p><p>I know. I can create Python script for this.</p><h4>Import Python Packages</h4><p>Open Jupyter Notebook then create a new notebook.</p><pre>import torch<br>from torch import nn<br>from torchvision import datasets, transforms<br>from torch.utils.data import DataLoader, ConcatDataset<br>import torch.optim as optim<br>import torch.optim.lr_scheduler as lr_scheduler<br>import numpy as np<br>import time<br>from sklearn.metrics import f1_score<br>import timm<br>from timm.models.layers import trunc_normal_<br>from ellzaf_ml.tools import EarlyStopping<br><br>EPOCHS = 500<br>PATIENCE = 3<br>BATCH_SIZE = 16<br>EPOCH_LEN = len(str(EPOCHS))<br>torch.manual_seed(39)</pre><p>In this code snippet, we import the PyTorch module along with its essential sub-modules for data loading and model training. Additionally, the sklearn.metrics module is imported for calculating the F1 score. The timm library is used for downloading pre-trained model. The trunc_normal_ function from timm.models.layers is utilized for initializing model weights using a truncated normal distribution, which can help in the effective training of neural networks.</p><p>Furthermore, the EarlyStopping from ellzaf_ml.tools, is implemented to apply early stopping strategies, saving the model only when there&#39;s no improvement in validation loss over a specified number of epochs. This will ensure we save the best performing model.</p><p>We also define several constants: EPOCHS, which specifies the total number of training epochs; PATIENCE, indicates the number of epochs to wait to see if the validation loss decreases; and BATCH_SIZE, determining the size of data batches during training. EPOCH_LEN is set for formatting textual outputs. Finally, we establish a seed for PyTorch&#39;s random number generator to ensure consistent and reproducible results in different runs of the model training process.</p><h4>Define Computing Device</h4><pre>device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>print(f&quot;Using {device} device&quot;)<br><br>device = torch.device(device)</pre><p>After that, we continue by defining our torch.device. This step is important as it explicitly sets the computing device for training the neural network model. It acts as a configuration tool, directing PyTorch to allocate tensors on either a CPU or a GPU.</p><h4>Load Dataset</h4><pre>class CustomDataset(datasets.ImageFolder):<br>    def __init__(self, root, special_augment_transform=None, general_augment_transform=None, special_classes=None):<br>        super().__init__(root)<br>        <br>        if special_augment_transform is not None and not callable(special_augment_transform):<br>            raise ValueError(&quot;special_augment_transform must be a callable or None&quot;)<br>        if general_augment_transform is not None and not callable(general_augment_transform):<br>            raise ValueError(&quot;general_augment_transform must be a callable or None&quot;)<br><br>        if special_classes is not None:<br>            if not isinstance(special_classes, (set, list, tuple)):<br>                raise TypeError(&quot;special_classes must be a set, list, or tuple&quot;)<br>            self.special_classes = set(special_classes)<br>        else:<br>            self.special_classes = set()<br><br>        self.special_augment_transform = special_augment_transform<br>        self.general_augment_transform = general_augment_transform<br><br>    def __getitem__(self, index):<br>        image, label = super().__getitem__(index)<br>        class_name = self.classes[label]<br>        if class_name in self.special_classes and self.special_augment_transform:<br>            image = self.special_augment_transform(image)<br>        elif self.general_augment_transform:<br>            image = self.general_augment_transform(image)<br><br>        return image, label</pre><p>For our experiment, we will use a custom dataset class by defining it as a subclass of datasets.ImageFolder. This class will take four arguments: root for the image path, special_augment_transform for augmenting our spoof images, general_augment_transform for augmenting our real images, and finally, special_classes to define the labels of our spoof images.</p><pre>transform_original = transforms.Compose([<br>    transforms.Resize(224),<br>    transforms.CenterCrop(224),<br>    transforms.ToTensor(),<br>    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),<br>])<br><br>transform_flipped = transforms.Compose([<br>    transforms.Resize(224),<br>    transforms.CenterCrop(224),<br>    transforms.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3),<br>    transforms.RandomHorizontalFlip(p=1),<br>    transforms.ToTensor(),<br>    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),<br>])<br><br>spoof_transforms = transforms.Compose([<br>    transforms.Resize(224),<br>    transforms.CenterCrop(224),<br>    transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5),<br>    transforms.RandomHorizontalFlip(p=1),<br>    transforms.GaussianBlur(kernel_size=3, sigma=(0.1, 2.0)),<br>    transforms.RandomGrayscale(p=0.1),<br>    transforms.ToTensor(),<br>])</pre><p>Now, we will proceed by defining our data transformation and augmentation. I plan to keep this simple, but feel free to add your own flavor or experiment with different values. For each transformation process, we use transforms.Resize(224) and transforms.CenterCrop(224). While these two processes might appear similar, they serve distinct purposes. transforms.Resize(224) scales the image so that the shorter side is 224 pixels, maintaining the aspect ratio. Then, transforms.CenterCrop(224) crops the center portion of this resized image to make it exactly 224x224 pixels.</p><pre>train_orig = datasets.ImageFolder(&quot;face_train&quot;, transform=transform_original)<br>train_flip = CustomDataset(root=&quot;face_train&quot;,<br>                           general_augment_transform=transform_flipped,<br>                           special_augment_transform=spoof_transforms,<br>                           special_classes=[&#39;fake&#39;])<br><br>train_data_combined = ConcatDataset([train_orig, train_flip])<br>train_loader = DataLoader(train_data_combined, batch_size=BATCH_SIZE, shuffle=True)<br><br>val_orig = datasets.ImageFolder(&quot;face_val&quot;, transform=transform_original)<br>val_flip = CustomDataset(root=&quot;face_val&quot;,<br>                           general_augment_transform=transform_flipped,<br>                           special_augment_transform=spoof_transforms,<br>                           special_classes=[&#39;fake&#39;])<br><br>val_data_combined = ConcatDataset([val_orig, val_flip])<br>val_loader = DataLoader(val_data_combined, batch_size=BATCH_SIZE, shuffle=False)<br><br>test_orig = datasets.ImageFolder(&quot;face_test&quot;, transform=transform_original)<br>test_loader = DataLoader(test_orig, batch_size=BATCH_SIZE, shuffle=False)</pre><p>With the previously created ‘face_train’ folder, we apply transform_original. Using CustomDataset, we apply transform_flipped to the original data and spoof_transforms for the fake data. After that, we concatenate train_orig and train_flip to form train_data_combined. Finally, we create a DataLoader with the previously defined constant BATCH_SIZE, setting shuffle to True. This shuffling is a common practice to promote model generalization. We follow a similar process for the validation data to create val_loader, except that we do not shuffle the data, as shuffling is not necessary for validation data. Lastly, for the test_orig, we only apply transform_original because we want to avoid altering the test data too much, ensuring it reflects real-world data scenarios.</p><pre>print(len(train_data_combined),len(val_data_combined),len(test_orig))</pre><p>You can use this method to check the number of data samples you have for the train, validation, and test sets.</p><h4>Model Training</h4><pre>def train_one_epoch(model, train_loader, device, optimizer, criterion, scheduler_lr=None):<br>    model.train()<br>    total_loss, total_f1, total_correct, total_samples, total_grad = 0, 0, 0, 0, 0<br><br>    for idx, (train_x_data, train_y_data) in enumerate(train_loader):<br>        train_x_data, train_y_data = train_x_data.to(device), train_y_data.to(device)<br>        optimizer.zero_grad()<br>        y_pred = model(train_x_data)<br><br>        loss = criterion(y_pred, train_y_data)<br>        loss.backward()<br>        grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 5.)<br>        optimizer.step()<br><br>        _, y_pred_max = torch.max(y_pred, dim=1)<br>        f1_score_val = f1_score(train_y_data.cpu(), y_pred_max.cpu(), average=&quot;macro&quot;)<br>        total_correct += (y_pred_max == train_y_data).sum().item()<br>        total_samples += train_y_data.size(0)<br>        total_loss += loss.item()<br>        total_f1 += f1_score_val.item()<br>        total_grad += grad_norm<br><br>        if idx % 10 == 0 and idx &gt; 0:<br>            lr = optimizer.param_groups[0][&#39;lr&#39;]<br>            print(<br>                f&#39;[{e:&gt;{EPOCH_LEN}}/{EPOCHS:&gt;{EPOCH_LEN}}] [{idx}/{len(train_loader)}] &#39;<br>                f&#39;lr {lr:.10f} | loss {loss:.10f} ({total_loss/idx:.4f}) | &#39;<br>                f&#39;grad_norm {grad_norm:.4f} ({total_grad/idx:.4f}) | &#39;<br>            )<br><br>    if scheduler_lr:<br>        scheduler_lr.step()<br>    avg_loss = total_loss / len(train_loader)<br>    avg_f1 = total_f1 / len(train_loader)<br>    avg_grad = total_grad / len(train_loader)<br>    accuracy = total_correct / total_samples<br>    return avg_loss, avg_f1, accuracy, avg_grad</pre><p>In this function, we train the model for one epoch. First, we set the model to training mode using model.train(), which affects layers like dropout and batch normalization, as they behave differently during training compared to inference. Next, we initialize variables to track the loss, F1 score, correct predictions, total samples, and gradient norm.</p><p>The training loop begins by enumerating train_loader, which allows us to obtain the batch index (idx) and track the model&#39;s performance during the epoch. This is especially useful if an epoch takes a long time to complete. In each iteration, we retrieve the training data (train_x_data) and labels (train_y_data) and move them to the current device (CUDA or CPU).</p><p>Before starting backpropagation, we set the gradients to zero using optimizer.zero_grad(). This is necessary because, by default, gradients are accumulated in PyTorch, and failing to zero them will lead to incorrect gradient calculations during successive backward passes. Therefore, explicitly setting them to zero before starting backpropagation prevents the mixing of gradient information from different batches, ensuring that each batch’s gradient calculation is independent of others.</p><p>We then compute the predictions (y_pred) using the model and calculate the loss by comparing y_pred with train_y_data using the specified criterion. The backward pass is performed using loss.backward(), which calculates the gradients. Gradient clipping is applied with torch.nn.utils.clip_grad_norm_(model.parameters(), 5.) to prevent exploding gradients, a problem where large gradients can cause the training process to diverge.</p><p>After computing the gradients, we update the model parameters with optimizer.step(). After completing those process for current batch, we calculate the F1 score and update counters for the total loss, F1 score, correct predictions, and gradient norm. Every 10 batches (or any number you want), we log important metrics like the current epoch, batch index, learning rate, average loss, and average gradient norm. This can be modified to include F1 score or accuracy tracking if desired.</p><p>Once all batches are processed, we step the learning rate scheduler, if provided, to update the learning rate. We then calculate the average loss, F1 score, gradient norm across all batches, and the epoch’s accuracy. Finally, the function returns these metrics for the epoch.</p><pre>def validate_one_epoch(model, val_loader, device, criterion, scheduler_lr=None):<br>    model.eval()<br>    total_loss, total_f1, total_correct, total_samples = 0, 0, 0, 0<br><br>    with torch.no_grad():<br>        for val_x_data, val_y_data in val_loader:<br>            val_x_data, val_y_data = val_x_data.to(device), val_y_data.to(device)<br>            y_val_pred = model(val_x_data)<br>            val_loss = criterion(y_val_pred, val_y_data)<br><br>            _, y_val_pred_max = torch.max(y_val_pred, dim=1)<br>            f1_score_val = f1_score(val_y_data.cpu(), y_val_pred_max.cpu(), average=&quot;macro&quot;)<br>            total_correct += (y_val_pred_max == val_y_data).sum().item()<br>            total_samples += val_y_data.size(0)<br>            total_loss += val_loss.item()<br>            total_f1 += f1_score_val.item()<br><br>    avg_loss = total_loss / len(val_loader)<br>    if scheduler_lr:<br>        scheduler_lr.step(avg_loss)<br>    avg_f1 = total_f1 / len(val_loader)<br>    accuracy = total_correct / total_samples<br>    return avg_loss, avg_f1, accuracy</pre><p>Previously, we defined a function to train the model for one epoch. Now, we define a function for validating the model for one epoch. Unlike the training function, we start with model.eval() to set the model in evaluation mode. Then, we initialize variables to track the validation loss, F1 score, correct predictions, and total samples.</p><p>Before proceeding with the validation loop, we use torch.no_grad() to disable gradient calculation, making the process more efficient. We then iterate through our val_loader to retrieve the data (val_x_data) and labels (val_y_data). We don&#39;t use enumerate this time because there&#39;s no need to track the process for each batch. As before, we assign our data to the specified device. However, unlike the training function, we don&#39;t use optimizer.zero_grad() as we are not updating the model; instead, we are evaluating it.</p><p>We proceed by performing model inference on val_x_data to obtain val_y_pred. Then, we calculate the loss by comparing val_y_pred and val_y_data. Again, we don&#39;t perform loss.backward() as this step is only for model training, not evaluation. We then compute the F1 score and update counters for the total loss, F1 score, correct predictions, and total samples. This process is repeated for each batch in the loop.</p><p>After completing the loop, we calculate the average loss. If a learning rate scheduler is defined, we update it based on the avg_loss. This is typically done for this <a href="https://pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.ReduceLROnPlateau.html">learning rate scheduler</a>. Then, we calculate the average F1 score and the overall accuracy. Finally, the function returns these metrics for the epoch.</p><pre>model = timm.create_model(&#39;vit_base_patch16_224.augreg_in21k_ft_in1k&#39;, pretrained=True)<br>model.head = torch.nn.Linear(model.head.in_features, 2)<br>trunc_normal_(model.head.weight, mean=0.0, std=0.02)<br>model = model.to(device)<br><br>criterion = nn.CrossEntropyLoss()<br><br>lr = 3e-5<br>optimizer = optim.Adam(model.parameters(), lr=lr)<br>scheduler_linear = lr_scheduler.LinearLR(optimizer, start_factor=0.01, total_iters=10)<br>scheduler_cosine = lr_scheduler.CosineAnnealingLR(optimizer, T_max=490, eta_min=lr/100)<br>scheduler_lr = lr_scheduler.SequentialLR(optimizer, [scheduler_linear,scheduler_cosine],milestones=[10])<br><br>early_stopping = EarlyStopping(<br>                    patience=PATIENCE,<br>                    verbose=True,<br>                    path=f&quot;weights/vit_teacher.pth&quot;,<br>                )<br><br>start_time = time.time()<br>for e in range(1, EPOCHS + 1):<br>    avg_loss_train, avg_f1_train, avg_accuracy_train, avg_grad = train_one_epoch(model, train_loader, device,<br>                                                                           optimizer, criterion, scheduler_lr)<br>    avg_loss_val, avg_f1_val, avg_accuracy_val = validate_one_epoch(model, val_loader, device, criterion)<br><br>    time_taken = time.time() - start_time<br>    time_format = time.strftime(&quot;%H:%M:%S&quot;, time.gmtime(time_taken))<br><br>    print(<br>    f&quot;[{e:&gt;{EPOCH_LEN}}/{EPOCHS:&gt;{EPOCH_LEN}}] Loss: {avg_loss_train:.5f} | &quot;<br>    + f&quot;F1-score: {avg_f1_train:.3f} | Acc: {avg_accuracy_train:.3f} | &quot;<br>    + f&quot;Val Loss: {avg_loss_val:.3f} | Val F1: {avg_f1_val:.3f} | &quot;<br>    + f&quot;Val Acc: {avg_accuracy_val:.3f} | {time_format}s | &quot;<br>    + f&quot;Grad: {avg_grad:.5f}&quot;<br>    )<br><br><br>    early_stopping(avg_loss_val, model)<br>    if early_stopping.early_stop:<br>        print(f&quot;Early stopping after {e} Epochs&quot;)<br>        break</pre><p>Now, we can finally begin training the teacher model. First, we define the pre-trained model that we want to use. I have chosen to use the base version of ViT with 16x16 patches, designed to take 224x224 pixel images as input. This model has been pre-trained with augmentation and regularization on ImageNet-21k and then fine-tuned on ImageNet-1k. You can explore more models <a href="https://github.com/huggingface/pytorch-image-models/blob/main/results/README.md">here</a>, ensure you pick one that accepts the same image size as your dataset. Since the model was initially fine-tuned on ImageNet-1k, its head layer is configured to predict 1,000 classes. However, our task only requires classification into 2 classes. To address this, we redefine the head layer to output only 2 classes. As this is a new layer, we use trunc_normal_ to initialize the weights for this layer. After this modification, we assign the model to the designated device.</p><p>Next, we define nn.CrossEntropyLoss as our criterion. For the model optimizer, we choose Adam with a learning rate of 3e-5. Note that the typical learning rate range for transformer-based models is around 1e-5 to 1e-4, but this can be adjusted based on your preferences or model requirements. We then create our learning rate scheduler by first defining a LinearLR for the initial 10 epochs, followed by a CosineAnnealingLR for a cosine decay over the remaining 490 epochs. We use SequentialLR to combine these two schedulers for sequential use. The learning rate will follow this pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*rSntF4Na2n4fxJrHOBEW9Q.png" /></figure><p>After initializing the model, loss function, optimizer, and schedulers, we then set up the EarlyStopping class. This is done using the previously defined constant PATIENCE, which determines how many epochs to wait before stopping the training if no improvement in validation loss is observed. Additionally, we specify a file path where the model will be saved whenever there&#39;s an improvement in the validation loss.</p><p>Next, we record the start_time before beginning our training and validation loops. This allows us to track the duration of the training process. The loops will iterate based on the constant EPOCHS we defined earlier. Since we have already defined our training and validation functions (train_one_epoch and validate_one_epoch), our main task within the loop is to log various metrics such as training loss, F1 score, accuracy, and validation loss after each epoch.</p><p>Following each epoch, we utilize the early stopping mechanism to check if the early stopping condition has been met. This is an important step to avoid overfitting and to stop the training process when the model ceases to improve on the validation dataset. If the early stopping condition is triggered, the training process will terminate early, indicating that further training is unlikely to result in better performance on the validation set.</p><h4>Model Testing</h4><p>My model began to overfit after the second epoch. In the second epoch, the validation loss was 0.045, the validation F1 score was 91.6%, and the validation accuracy was 98.5%.</p><p>Now, we will test the model using the test dataset. The importance of having a test dataset is to ensure that the model performs consistently with data it has never encountered before.</p><pre>model = timm.create_model(&#39;vit_base_patch16_224.augreg_in21k_ft_in1k&#39;, pretrained=True)<br>model.head = torch.nn.Linear(model.head.in_features, 2)<br>model = model.to(device)<br>model.load_state_dict(<br>    torch.load(<br>        &quot;weights/vit_teacher.pth&quot;<br>    )<br>)<br>model.eval()<br><br>with torch.no_grad():<br>    correct = 0<br>    tp = 0<br>    tn = 0<br>    fp = 0<br>    fn = 0<br><br>    for data, target in test_loader:<br>        data, target = data.to(device), target.to(device)<br>        output = model(data)<br>        pred = output.argmax(dim=1, keepdim=True)<br><br>        tp += (pred.eq(1) &amp; target.eq(1).view_as(pred)).sum().item()<br>        tn += (pred.eq(0) &amp; target.eq(0).view_as(pred)).sum().item()<br>        fp += (pred.eq(1) &amp; target.eq(0).view_as(pred)).sum().item()<br>        fn += (pred.eq(0) &amp; target.eq(1).view_as(pred)).sum().item()<br><br>        correct += pred.eq(target.view_as(pred)).sum().item()<br><br>    accuracy = correct / len(test_loader.dataset)<br>    far = fp / (fp + tn)<br>    frr = fn / (fn + tp)<br><br>    recall = tp / (tp + fn)<br><br>    hter = (far + frr ) / 2<br><br>    print(f&quot;test acc: {accuracy * 100}%&quot;)<br>    print(f&quot;recall: {recall * 100}%&quot;)<br>    print(f&quot;far: {far * 100}%&quot;)<br>    print(f&quot;frr: {frr * 100}%&quot;)<br>    print(f&quot;hter: {hter * 100}%&quot;)</pre><p>Similar to previous steps, we need to load the model and then modify the model’s head layer. This time, we will not perform weight initialization for the new layer because our goal is to maintain the same model architecture as the one used during training. This ensures that we can load the weights of the previously trained model.</p><p>After loading the model, we switch it to evaluation mode using model.eval(). Subsequently, we use torch.no_grad() to initiate model inference. We calculate the true positives, true negatives, false positives, and false negatives based on the model’s predictions. From these values, we can derive several evaluation metrics, including test accuracy, recall, false acceptance rate (FAR), false rejection rate (FRR), and half total error rate (HTER). We focus on the recall value because it measures the system’s ability to correctly identify all instances of a particular class.</p><p>My model achieved a test accuracy of 99.78%, a recall of 99.91%, a FAR of 0.311, an FRR of 0.09, and an HTER of 0.2%. Your model might achieve somewhat similar number to my models.</p><p>We will continue Masked Image Modelling for student model in Part 3.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b9c8794ab7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PyTorch and Face Liveness Detection: A Comprehensive Guide]]></title>
            <link>https://medium.com/@hazqeelafyq09/pytorch-and-face-liveness-detection-a-comprehensive-guide-007b926bb222?source=rss-c4e459d69bfe------2</link>
            <guid isPermaLink="false">https://medium.com/p/007b926bb222</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[face-liveness]]></category>
            <dc:creator><![CDATA[Hazqeel Afyq]]></dc:creator>
            <pubDate>Sun, 14 Jan 2024 16:22:47 GMT</pubDate>
            <atom:updated>2024-01-16T15:35:58.917Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aS0ZHhwmiUOhUK5g" /></figure><p>While the world increasingly turns its focus to the wonders of facial recognition technology, an equally critical aspect often slips under the radar — face liveness detection. It might not always be needed for facial recognition, but in situations where security and authenticity are crucial, face liveness is implemented.</p><p>A common example of face liveness is in eKYC (electronic Know Your Customer) processes, such as when creating an account for an e-wallet or online trading. The process might seem straightforward, where you need to capture your face. However, this entire procedure is an application of face liveness detection. Face liveness can be divided into two types: active and passive.</p><p><strong>Active Face Liveness:</strong></p><ul><li>Requires user to do action such as blinking or smiling.</li><li>More challenging to spoof.</li><li>Longer completion time.</li><li>Could be problematic for users with disabilities affecting smiling or blinking.</li></ul><p><strong>Passive Face Liveness:</strong></p><ul><li>Operates using just the user’s image.</li><li>Easier to spoof.</li><li>Faster to complete.</li><li>More inclusive and accessible.</li></ul><p>For this walkthrough, we will embark on creating a passive face liveness detection system using PyTorch, complemented by an example dataset available online. Our journey will unfold through the following steps:</p><ol><li>Research Papers Overview.</li><li>Data Acquisition.</li><li>Train Teacher Model.</li><li>Pre-train Student Model.</li><li>Distillation.</li></ol><h3>Research Papers Overview</h3><p>The models that we will use are Vision Transformer (ViT) integrated with additional architectures, SimMIM and Feature Distillation.</p><h4><strong>ViT:</strong></h4><figure><img alt="Vision Transformer Architecture" src="https://cdn-images-1.medium.com/max/1024/1*dQ6BkKf9REUYIZrrhv7s8g.png" /><figcaption>ViT architecture from An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale</figcaption></figure><p><a href="https://arxiv.org/abs/2010.11929">ViT</a> divides an image into patches of a predefined size and applies a linear embedding transformation to each patch. Additionally, it incorporates position embeddings to represent the spatial information of these patches. Finally, it feeds the resulting sequence of embedded vectors into a conventional Transformer encoder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Chih-WDJCS3-n1c2LV8tiQ.png" /><figcaption>Shifted Window Approach from Swin Transformer: Hierarchical Vision Transformer using Shifted Windows</figcaption></figure><p>We intend to utilize a ViT that incorporates elements of the <a href="https://arxiv.org/abs/2103.14030">Swin </a>Transformer architecture. This includes the introduction of relative position bias and window-based self-attention. The relative position bias is designed to encode precise spatial relationships that are sensitive to the content of the image. Meanwhile, the window-based self-attention focuses on local features, as opposed to global features. This method means that the model has to use both the local attention and the relative position bias together to really get a good understanding of the whole image. The code we plan to use is a modified version based on this <a href="https://github.com/microsoft/SimMIM/blob/main/models/vision_transformer.py">repository</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdv6G9SXacR4e_T-7IWqBQ.png" /><figcaption>GFNet Architecture from Global Filter Networks for Image Classification</figcaption></figure><p>We will also experiment with the Global Filter, as used in <a href="https://arxiv.org/abs/2107.00645">GFNet</a>. This approach is similarly utilized in the <a href="https://arxiv.org/abs/2304.06446">SpectFormer</a>, where it combines both Spectral Blocks and Attention Blocks. For our experiment, we will create a variation that combines both Attention and Spectral elements within each block. We have chosen to use ‘Spectral’ instead of ‘Global Filter’ in our terminology because ‘Spectral’ sounds cooler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*qTxiXeNbM6jJaE2ZGjnEIg.png" /><figcaption>Implementation of RoPE from RoFormer: Enhanced Transformer with Rotary Position Embedding</figcaption></figure><p>In addition to our current experimentation, we will integrate Rotary Position Embedding (RoPE) from <a href="https://arxiv.org/abs/2104.09864v5">RoFormer</a> into our model’s architecture. RoPE uniquely encodes the absolute positions within an image using a rotation matrix, which is particularly effective in maintaining positional information. Simultaneously, it introduces an explicit representation of relative positional relationships within the self-attention mechanism of the model.</p><h4><strong>SimMIM:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqpAl4NxrOhiE2WG_wjjlw.png" /><figcaption>SimMIM architecture from SimMIM: A Simple Framework for Masked Image Modeling</figcaption></figure><p><a href="https://arxiv.org/abs/2111.09886">SimMIM</a> is a straightforward framework for masked image modeling. It employs only a single-layer prediction head to predict raw pixel values of randomly masked patches and conducts learning using a simple ℓ1 loss. The research paper conducted a study on ViT and Swin models. Since we will be using ViT, our focus will be on ViT parameters. The study experimented with different masking strategies and various masked patch sizes, ultimately achieving the best result with a random masking strategy using a patch size of 32×32 and a mask ratio of 0.5. However, for our use case, we will follow the default option opted in the study, which is a mask ratio of 0.6.</p><h4><strong>Feature Distillation:</strong></h4><figure><img alt="Feature Distillation Architecture" src="https://cdn-images-1.medium.com/max/1024/1*vO_cHSUkFv1R9sY2S1nkrg.png" /><figcaption>Distillation architecture from Understanding the Role of the Projector in Knowledge Distillation</figcaption></figure><p>This <a href="https://arxiv.org/abs/2303.11098">paper</a> proposes the use of normalization, projection layers, and the soft maximum function for knowledge distillation. The entire process essentially involves adding linear projection and batch normalization to the student model, along with adding batch normalization to the teacher model’s feature output. Subsequently, it compares the feature space between the student model and the teacher model using the logsum distance metric. The loss function employed for this approach consists of both the task loss and the feature distillation loss.</p><h3>Data Acquisition</h3><p>For this walkthrough, we will use a publicly available dataset for experimentation. Specifically, we will be utilizing the NUAA dataset, which can be downloaded from <a href="https://parnec.nuaa.edu.cn/_upload/tpl/02/db/731/template731/pages/xtan/NUAAImposterDB_download.html">here</a>. Since our primary focus is on face liveness, we will use the second dataset, which already includes the output of face images.</p><h3>Python</h3><p>Before proceeding further, please create a Python environment and install the necessary Python packages.</p><pre>pip install ellzaf_ml numpy optuna jupyter notebook tensorboard scikit-learn</pre><p>Training teacher model will be continued in Part 2.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=007b926bb222" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>