극심한 데이터 희소성 시나리오를 위한 Human-Aligned Decision Transformers 기반 심해 탐사 서식지 설계

발행: (2025년 12월 20일 오전 06:24 GMT+9)
15 min read
원문: Dev.to

I’m happy to translate the article for you, but I’ll need the full text you’d like translated. Could you please paste the content (or the portion you want translated) here? I’ll keep the source link exactly as you provided and preserve all formatting, markdown, and code blocks.

Source:

소개: 심연으로부터의 교훈

실패한 시뮬레이션에서 시작되었습니다. 저는 자율 수중 차량(AUV) 항해를 위한 강화학습 에이전트를 실험하면서, 시뮬레이션된 심해 환경에서 서식지 배치를 최적화하려고 했습니다. 에이전트는 테라바이트 규모의 합성 수심 데이터, 해류 모델, 자원 지도에 접근할 수 있었습니다. 그러나 초기 서식지 설계를 해양 생물학자와 베테랑 잠수 파일럿에게 제시했을 때, 그들의 일치된 반응은 다음과 같았습니다:

“이건 실제 바다에서는 절대 작동하지 않을 거야.”

그 단절은 심각했습니다. 제 AI 시스템은 에너지 효율성과 구조적 안정성을 최적화했지만, 인간 요소를 완전히 놓쳤습니다:

  • 연구원들이 실제로 어디에서 작업하고 싶어 할까?
  • 극한 압력 하에서 비상 절차는 어떻게 작동할까?
  • 미묘한 환경 신호—해류 패턴, 퇴적물 안정성, 지역 동물 행동—중 경험 많은 해양학자에게 가장 중요한 것은 무엇일까?

이 경험은 저를 연구의 토끼굴로 이끌었고, 이는 극한 환경을 위한 AI 접근 방식을 근본적으로 바꾸어 놓았습니다. 오프라인 강화학습과 트랜스포머 아키텍처를 탐구하면서, 저는 중요한 격차를 발견했습니다: 가장 진보된 의사결정 시스템조차 인간 전문 지식이 가장 필요한, 데이터가 희박하고 위험이 높은 영역에서 정확히 실패하고 있었습니다—여기서는 모든 관측이 소중하고 실수가 치명적입니다.

Decision Transformers와 인간‑인‑루프 AI에 대한 최신 돌파구를 연구하면서, 우리는 새로운 패러다임이 필요하다는 것을 깨달았습니다: 데이터만 학습하는 것이 아니라, 극한 불확실성 하에서 인간의 의사결정 과정에 맞추어 학습하는 시스템. 이 글은 지구상 가장 도전적인 프론티어 중 하나를 위해 인간 정렬 의사결정 트랜스포머(Human‑Aligned Decision Transformers)를 개발한 저의 여정을 기록합니다.

Deep‑Sea AI의 “세 가지 제약”

  1. Extreme Data Sparsity – 단일 잠수는 비용이 $50,000 정도 들고 특정 위치에서 몇 시간의 관측만 제공할 수 있습니다.
  2. High‑Dimensional State Space – 압력, 온도, 염도, 해류, 지형, 생물 활동 및 장비 상태.
  3. Irreversible Decisions – 서식지 배치 결정은 4,000 m 깊이에 배치된 후에는 쉽게 수정할 수 없습니다.

전통적인 딥 RL 방법은 수백만 번의 환경 상호작용을 필요로 했으며—실제 심해 작업에서는 명백히 불가능했습니다. 오프라인 RL은 가능성을 제시했지만, 인간 전문가가 데이터에 포착되지 않은 암묵적 지식을 기반으로 결정을 내릴 때 발생하는 분포 이동 문제에 시달렸습니다.

왜 트랜스포머가 중요한가

트랜스포머 아키텍처에 대한 나의 실험에서 흥미로운 발견 중 하나는 희소하고 불규칙한 관측을 가진 시퀀스를 모델링하는 놀라운 능력이었다. Decision Transformer 논문(Chen et al., 2021)을 공부하면서, 시간적 거리에 관계없이 관련된 과거 경험을 가중치로 평가하는 어텐션 메커니즘의 능력이 일상적인 작업이 며칠 또는 몇 주 동안 지속되는 심해 시나리오에서 의미 있는 사건들이 떨어져 있을 때 특히 적합하다는 것을 깨달았다.

인간 보상 구조는 다목적이다

극한 환경의 인간 전문가들은 단일 보상 함수에 최적화하지 않는다. 그들은 여러 개의, 때로는 상충되는 목표를 유지하며 상황에 따라 동적으로 우선순위를 재조정한다.

  • 배치 단계 – 구조적 무결성을 우선시한다.
  • 운용 단계 – 과학적 접근성을 우선시한다.
  • 폭풍/비상 단계 – 신속한 탈출 및 안전을 우선시한다.

역강화학습은 제한된 시연 데이터로부터 이러한 복잡하고 상황에 의존적인 보상 구조를 학습하려면 근본적으로 다른 접근 방식이 필요함을 보여주었다. 인지과학 문헌은 인간이 “청킹”(chunking)—관련 개념과 행동을 고차원 단위로 묶는—을 사용하여 고스트레스 상황에서 복잡성을 관리한다는 것을 밝혀냈다.

핵심 혁신

핵심 혁신은 여러 연구 흐름을 결합함으로써 등장했습니다.

import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import GPT2Model

class HumanAlignedDecisionTransformer(nn.Module):
    """
    A Decision Transformer variant that aligns with human cognitive processes
    through multi‑scale attention and explicit uncertainty modeling.
    """
    def __init__(self, state_dim, act_dim, hidden_dim=256,
                 n_layers=6, n_heads=8, max_len=512):
        super().__init__()

        # Multi‑scale state encoders
        self.local_encoder = nn.Sequential(
            nn.Linear(state_dim, hidden_dim),
            nn.LayerNorm(hidden_dim),
            nn.GELU()
        )
        self.context_encoder = nn.Sequential(
            nn.Linear(state_dim * 10, hidden_dim),   # Temporal context
            nn.LayerNorm(hidden_dim),
            nn.GELU()
        )

        # Human preference embedding (10 distinct preference modes)
        self.preference_embedding = nn.Embedding(10, hidden_dim)

        # GPT‑based decision transformer backbone
        self.transformer = GPT2Model.from_pretrained('gpt2')
        transformer_dim = self.transformer.config.hidden_size

        # Adaptive projection layers
        self.state_projection   = nn.Linear(hidden_dim, transformer_dim)
        self.action_projection  = nn.Linear(act_dim, transformer_dim)
        self.return_projection  = nn.Linear(1, transformer_dim)

        # Uncertainty‑aware output heads
        self.action_head      = nn.Linear(transformer_dim, act_dim * 2)  # Mean & variance
        self.value_head       = nn.Linear(transformer_dim, 1)
        self.uncertainty_head = nn.Linear(transformer_dim, 1)            # Epistemic uncertainty

        # Human feedback integration
        self.feedback_attention = nn.MultiheadAttention(
            transformer_dim, n_heads, batch_first=True
        )

    def forward(self, states, actions, returns, timesteps,
                preferences, feedback=None):
        """
        Parameters
        ----------
        states      : Tensor (B, T, state_dim)
        actions     : Tensor (B, T, act_dim)
        returns     : Tensor (B, T, 1)
        timesteps   : Tensor (B, T) – positional encoding for temporal order
        preferences : Tensor (B, T) – indices into preference_embedding
        feedback    : Optional Tensor (B, T, transformer_dim) – human‑in‑the‑loop signals
        """
        # Encode local and contextual state information
        local_feat   = self.local_encoder(states)                     # (B, T, hidden_dim)
        # Simplified context concatenation
        context_input = states.view(states.size(0), -1)               # (B, state_dim * T)
        context_feat  = self.context_encoder(context_input).unsqueeze(1).repeat(1, states.size(1), 1)

        # Combine local and contextual embeddings
        state_feat = local_feat + context_feat

        # Add human preference embedding
        pref_embed = self.preference_embedding(preferences)          # (B, T, hidden_dim)
        state_feat = state_feat + pref_embed

        # Project to transformer dimension
        state_proj   = self.state_projection(state_feat)
        action_proj  = self.action_projection(actions)
        return_proj  = self.return_projection(returns)

        # Concatenate tokens for the GPT‑style transformer
        transformer_input = torch.cat([return_proj, state_proj, action_proj], dim=-1)

        # Pass through the transformer backbone
        transformer_out = self.transformer(inputs_embeds=transformer_input).last_hidden_state

        # Optional feedback attention
        if feedback is not None:
            transformer_out, _ = self.feedback_attention(
                transformer_out, feedback, feedback
            )

        # Output heads
        action_out      = self.action_head(transformer_out)          # (B, T, act_dim*2)
        value_out       = self.value_head(tr

위 코드는 최소한의, 예시적인 프로토타입입니다; 실제 생산‑등급 시스템은 안정성, 안전‑중요 검증, 그리고 해양‑등급 하드웨어와의 통합을 위한 추가 엔지니어링이 필요합니다.

Source:

요약

ChallengeTraditional RL LimitationHuman‑Aligned DT Advantage
데이터 희소성수백만 번의 상호작용 필요긴 시간대에 걸친 어텐션을 활용해, 적은 관측치에서도 최대 신호를 추출
다목표 트레이드오프단일 스칼라 보상 → 과도한 단순화선호 임베딩이 상황‑의존적 목표를 인코딩
인간 전문지식암묵적 지식 포착 어려움피드백‑어텐션 모듈이 실시간 인간 입력을 통합
불확실성종종 무시 → 위험한 배포별도 불확실성 헤드가 인식적 추정을 제공, 안전‑실패 메커니즘을 지원

향후 방향

  1. Real‑world trials – 파일럿 AUV 플랫폼에 배치하여 현장(in situ)에서 해양 과학자와의 정렬을 검증한다.
  2. Meta‑learning of preferences – 모델이 소수의 시연(demonstrations)으로부터 새로운 선호 모드를 추론하도록 허용한다.
  3. Robustness to distribution shift – 베이지안 신경망 기법과 결합하여 새로운 해양 환경에서의 인식적 불확실성(epistemic uncertainty)을 보다 잘 정량화한다.
  4. Explainability dashboards – 어텐션 가중치와 선호 임베딩을 시각화하여 인간 운영자가 모델 추론을 감사할 수 있게 한다.

심해 탐사는 공학과 인공지능의 경계를 확장한다. 인간 인지를 존중하고 통합하는 Decision Transformer를 구축함으로써, 우리는 지구에서 가장 접근하기 어려운 최전선에서 안전하고 효과적이며 과학적으로 생산적인 임무에 한 걸음 더 다가간다.

인간 정렬 구성 요소가 포함된 모델 포워드 패스

def forward(self, states, actions, returns, timesteps,
            preferences=None, human_feedback=None):
    """
    Forward pass with human alignment components
    """
    batch_size, seq_len = states.shape[:2]

    # Encode states at multiple scales
    local_features = self.local_encoder(states)

    # Create temporal context windows
    context_windows = self._create_context_windows(states)
    context_features = self.context_encoder(context_windows)

    # Combine features
    state_features = local_features + 0.3 * context_features

    if preferences is not None:
        pref_emb = self.preference_embedding(preferences)
        state_features = state_features + pref_emb.unsqueeze(1)

    # Project to transformer dimensions
    state_emb = self.state_projection(state_features)
    action_emb = self.action_projection(actions)
    return_emb = self.return_projection(returns.unsqueeze(-1))

    # Create transformer input sequence: [return, state, action] per timestep
    sequence = torch.stack([return_emb, state_emb, action_emb], dim=2)
    sequence = sequence.reshape(batch_size, 3 * seq_len, -1)

    # Add positional encoding
    positions = torch.arange(seq_len, device=states.device).repeat_interleave(3)
    position_emb = self.positional_encoding(positions, sequence.size(-1))
    sequence = sequence + position_emb.unsqueeze(0)

    # Transformer processing
    transformer_output = self.transformer(
        inputs_embeds=sequence,
        output_attentions=True
    )

    # Extract decision representations
    decision_embeddings = transformer_output.last_hidden_state[:, 1::3, :]

    # Integrate human feedback if available
    if human_feedback is not None:
        feedback_emb = self._encode_feedback(human_feedback)
        decision_embeddings, _ = self.feedback_attention(
            decision_embeddings, feedback_emb, feedback_emb
        )

    # Uncertainty‑aware predictions
    action_params = self.action_head(decision_embeddings)
    action_mean, action_logvar = torch.chunk(action_params, 2, dim=-1)
    action_var = torch.exp(action_logvar)

    values = self.value_head(decision_embeddings)
    epistemic_uncertainty = torch.sigmoid(self.uncertainty_head(decision_embeddings))

    return {
        'action_mean': action_mean,
        'action_var': action_var,
        'values': values,
        'epistemic_uncertainty': epistemic_uncertainty,
        'attention_weights': transformer_output.attentions
    }

헬퍼 메서드

def _create_context_windows(self, states):
    """Create multi‑scale temporal context windows"""
    # Implementation for creating context windows at different time scales
    pass

def _encode_feedback(self, feedback):
    """Encode human feedback into transformer space"""
    pass

def positional_encoding(self, position, d_model):
    """Sinusoidal positional encoding"""
    angle_rates = 1 / torch.pow(10000,
                               (2 * (torch.arange(d_model) // 2)) / d_model)
    angle_rads = position.unsqueeze(-1) * angle_rates.unsqueeze(0)

    # Apply sin to even indices, cos to odd indices
    angle_rads[:, 0::2] = torch.sin(angle_rads[:, 0::2])
    angle_rads[:, 1::2] = torch.cos(angle_rads[:, 1::2])

    return angle_rads

Architectural Insights

멀티‑스케일 인코딩은 인간 전문가가 동시에 고려하는 방식을 모방하는 데 결정적이었다:

  • 즉각적인 센서 판독값 (local)
  • 보다 넓은 환경 패턴 (context)

선호 임베딩 시스템은 모델이 임무 단계—배치, 정상 운영, 또는 비상 상황—에 따라 의사결정 스타일을 조정하도록 합니다.

극심한 데이터 희소성에 대한 훈련 방법론

class SparseDataTrainer:
    """
    Training methodology for extreme data sparsity scenarios
    """
    def __init__(self, model, optimizer, config):
        self.model = model
        self.optimizer = optimizer
        self.config = config

        # Multiple loss components
        self.mse_loss = nn.MSELoss()
        self.kl_loss = nn.KLDivLoss(reduction='batchmean')

    def train_step(self, batch, human_demonstrations,
                   feedback_trajectories=None):
        """
        Training step with multiple data sources and alignment objectives
        """
        states, actions, returns, timesteps = batch

        # Standard behavior cloning loss
        outputs = self.model(states, actions, returns, timesteps)
        bc_loss = self._behavior_cloning_loss(outputs, actions)

        # Uncertainty regularization
        uncertainty_loss = self._uncertainty_regularization(
            outputs['epistemic_uncertainty']
        )

        # Human demonstration alignment
        alignment_loss = 0
        if human_demonstrations is not None:
            alignment_loss = self._human_alignment_loss(
                outputs, human_demonstrations
            )

        # Feedback integration loss (if available)
        feedback_loss = 0
        if feedback_trajectories is not None:
            feedback_loss = self._feedback_integration_loss(
                outputs, feedback_trajectories
            )

        # Attention pattern regularization
        attention_loss = self._attention_regularization(
            outputs['attention_weights']
        )

        # Composite loss
        total_loss = (
            self.config.bc_weight * bc_loss +
            self.config.uncertainty_weight * uncertainty_loss +
            self.config.alignment_weight * alignment_loss +
            self.config.feedback_weight * feedback_loss +
            self.config.attention_weight * attention_loss
        )
        return total_loss, {
            'bc_loss': bc_loss,
            'uncertainty_loss': uncertainty_loss,
            'alignment_loss': alignment_loss,
            'feedback_loss': feedback_loss,
            'attention_loss': attention_loss
        }

최적화

self.optimizer.zero_grad()
total_loss.backward()
torch.nn.utils.clip_grad_norm_(self.model.parameters(), 1.0)
self.optimizer.step()

return {
    'total_loss': total_loss.item(),
    'bc_loss': bc_loss.item(),
    'alignment_loss': alignment_loss.item() if human_demonstrations else 0,
    'attention_sparsity': self._compute_attention_sparsity(
        outputs['attention_weights']
    )
}

인간‑정렬 손실

def _human_alignment_loss(self, model_outputs, human_demos):
    """
    인간 시연 궤적과 모델 결정을 최적 수송 및 선호 학습을 사용해 정렬합니다
    """
    # 의사결정 임베딩 추출
    # (구현 세부 사항은 간략히 생략)
    pass
Back to Blog

관련 글

더 보기 »

창고 활용에 대한 종합 가이드

소개 창고는 근본적으로 3‑D 박스일 뿐입니다. Utilisation은 실제로 그 박스를 얼마나 사용하고 있는지를 측정하는 지표입니다. While logistics c...