""" Core implementation of Soft Thinking for Snow Spike. Based on the paper "Soft Thinking: Unlocking the Reasoning Potential of LLMs in Continuous Concept Space" by Zhang et al. (2025). Key concepts: 1. Concept tokens: Probability distributions over characters instead of discrete selection 2. Continuous concept space: Weighted character embeddings 3. Cold Stop: Entropy-based early stopping to prevent generation collapse """ import numpy as np import logging from typing import List, Dict, Tuple, Optional, Any, NamedTuple import math logger = logging.getLogger("snow_spike.soft_thinking") class ConceptToken(NamedTuple): """ A concept token representing a probability distribution over characters. Unlike discrete token selection, this maintains the full distribution enabling "soft" reasoning through multiple possible paths. """ probabilities: np.ndarray # Probability distribution over characters characters: List[str] # List of characters corresponding to probabilities entropy: float # Shannon entropy of the distribution def get_weighted_embedding(self, embeddings: Dict[str, np.ndarray]) -> np.ndarray: """ Compute the weighted embedding in continuous concept space. Args: embeddings: Dictionary mapping characters to their embeddings Returns: weighted_embedding: Probability-weighted sum of character embeddings """ weighted_sum = np.zeros_like(next(iter(embeddings.values()))) for char, prob in zip(self.characters, self.probabilities): if char in embeddings: weighted_sum += prob * embeddings[char] return weighted_sum def sample_character(self, temperature: float = 1.0) -> str: """Sample a character from this concept token's distribution.""" if temperature == 0: # Deterministic selection return self.characters[np.argmax(self.probabilities)] # Apply temperature scaling scaled_probs = np.power(self.probabilities, 1/temperature) scaled_probs /= np.sum(scaled_probs) return np.random.choice(self.characters, p=scaled_probs) class ColdStopController: """ Implements Cold Stop mechanism to prevent generation collapse. Monitors entropy of concept tokens and stops generation when the model becomes overconfident (low entropy) for consecutive steps. """ def __init__(self, entropy_threshold: float = 0.05, consecutive_steps: int = 3): """ Initialize Cold Stop controller. Args: entropy_threshold: Entropy below which is considered "cold" (confident) consecutive_steps: Number of consecutive cold steps before stopping """ self.entropy_threshold = entropy_threshold self.consecutive_steps = consecutive_steps self.low_entropy_count = 0 self.history = [] def should_stop(self, entropy: float) -> bool: """ Check if generation should stop based on entropy. Args: entropy: Current concept token entropy Returns: should_stop: True if generation should stop """ self.history.append(entropy) if entropy < self.entropy_threshold: self.low_entropy_count += 1 logger.debug(f"Low entropy step: {self.low_entropy_count}/{self.consecutive_steps}") else: self.low_entropy_count = 0 return self.low_entropy_count >= self.consecutive_steps def reset(self): """Reset the controller state.""" self.low_entropy_count = 0 self.history = [] class SoftThinkingGenerator: """ Main class for Soft Thinking text generation in Snow Spike. Replaces discrete character selection with probabilistic concept tokens, enabling reasoning in continuous concept space. """ def __init__(self, network, encoder, projection, top_k: int = 15, cold_stop_entropy: float = 0.05, cold_stop_steps: int = 3): """ Initialize Soft Thinking generator. Args: network: SequentialAdaptiveNetwork instance encoder: TextSpikeEncoder instance projection: InputProjection instance top_k: Number of top characters to consider for concept token cold_stop_entropy: Entropy threshold for Cold Stop cold_stop_steps: Consecutive steps for Cold Stop """ self.network = network self.encoder = encoder self.projection = projection self.top_k = top_k self.cold_stop = ColdStopController(cold_stop_entropy, cold_stop_steps) # Create character embeddings from spike patterns self.char_embeddings = self._create_character_embeddings() def _create_character_embeddings(self) -> Dict[str, np.ndarray]: """Create embeddings for each character based on their spike patterns.""" embeddings = {} for char, spike_pattern in self.encoder.char_to_spikes.items(): # Convert spike pattern to numpy array embeddings[char] = np.array(spike_pattern, dtype=np.float32) return embeddings def generate_text(self, seed_text: str, max_length: int = 100, temperature: float = 0.8, use_cold_stop: bool = True) -> str: """ Generate text using Soft Thinking approach. Args: seed_text: Initial text to start generation max_length: Maximum number of characters to generate temperature: Temperature for sampling (0 = deterministic) use_cold_stop: Whether to use Cold Stop mechanism Returns: generated_text: Complete text including seed """ logger.info(f"Soft Thinking generation starting with: '{seed_text[:30]}...'") generated = seed_text self.cold_stop.reset() for i in range(max_length): # Get recent context (last 32 characters) context = generated[-32:] if len(generated) > 32 else generated # Generate concept token concept_token = self._generate_concept_token(context) # Check Cold Stop if use_cold_stop and self.cold_stop.should_stop(concept_token.entropy): logger.info(f"Cold Stop triggered at step {i} (entropy: {concept_token.entropy:.4f})") break # Sample character from concept token next_char = concept_token.sample_character(temperature) generated += next_char # Stop on sentence endings if next_char in '.!?\n' and i > 10: break return generated def _generate_concept_token(self, context: str) -> ConceptToken: """ Generate a concept token for the given context. This is the core of Soft Thinking - instead of selecting a single character, we maintain a probability distribution over all possible next characters. """ # Encode context spikes = self.encoder.encode_text(context) flat_input = self.encoder.flatten_sequence(spikes) # Project to network input size projected_input = self.projection.project(flat_input) # Get network output output = self.network.forward(projected_input) # Convert output to probability distribution return self._output_to_concept_token(output) def _output_to_concept_token(self, output: List[float]) -> ConceptToken: """ Convert network output to a concept token. This creates a probability distribution over characters based on the network's output activations. """ chars = list(self.encoder.char_to_spikes.keys()) # Different strategies based on output dimensions if len(output) == len(chars): # Direct mapping: output corresponds to character probabilities scores = np.array(output) elif len(output) == self.encoder.encoding_width: # Output is a spike pattern - compare with all character patterns scores = [] output_pattern = np.array(output) for char in chars: char_pattern = np.array(self.encoder.char_to_spikes[char]) # Use cosine similarity for continuous outputs similarity = np.dot(output_pattern, char_pattern) / ( np.linalg.norm(output_pattern) * np.linalg.norm(char_pattern) + 1e-8 ) scores.append(similarity) scores = np.array(scores) else: # Generic case: map output to character space using learned patterns # This uses the network's learned representations scores = self._map_output_to_char_scores(output, chars) # Apply softmax to get probabilities # Prevent overflow by subtracting max scores_exp = np.exp(scores - np.max(scores)) probabilities = scores_exp / np.sum(scores_exp) # Keep only top-k characters for efficiency if self.top_k < len(chars): top_indices = np.argpartition(probabilities, -self.top_k)[-self.top_k:] top_chars = [chars[i] for i in top_indices] top_probs = probabilities[top_indices] # Renormalize top_probs = top_probs / np.sum(top_probs) else: top_chars = chars top_probs = probabilities # Calculate entropy entropy = -np.sum(top_probs * np.log(top_probs + 1e-10)) return ConceptToken( probabilities=top_probs, characters=top_chars, entropy=entropy ) def _map_output_to_char_scores(self, output: List[float], chars: List[str]) -> np.ndarray: """ Map arbitrary-sized output to character scores. This handles cases where the output dimension doesn't directly correspond to characters or spike patterns. """ output_array = np.array(output) scores = [] # Use a learned mapping based on output patterns for char in chars: # Get character's spike pattern char_pattern = np.array(self.encoder.char_to_spikes[char]) # Create a projection of output to match character pattern size if len(output) > len(char_pattern): # Downsample output indices = np.linspace(0, len(output)-1, len(char_pattern), dtype=int) projected_output = output_array[indices] else: # Upsample output projected_output = np.interp( np.linspace(0, len(output)-1, len(char_pattern)), np.arange(len(output)), output_array ) # Calculate similarity similarity = np.dot(projected_output, char_pattern) / ( np.linalg.norm(projected_output) * np.linalg.norm(char_pattern) + 1e-8 ) scores.append(similarity) return np.array(scores) # Convenience functions for easy integration def soft_thinking_generate_text(network, encoder, projection, seed_text: str, max_length: int = 100, temperature: float = 0.8, top_k: int = 15) -> str: """ Convenience function for Soft Thinking text generation. Args: network: SequentialAdaptiveNetwork instance encoder: TextSpikeEncoder instance projection: InputProjection instance seed_text: Initial text max_length: Maximum generation length temperature: Sampling temperature top_k: Number of top characters to consider Returns: generated_text: Generated text """ generator = SoftThinkingGenerator(network, encoder, projection, top_k=top_k) return generator.generate_text(seed_text, max_length, temperature) def output_to_concept_token(output: List[float], encoder, top_k: int = 15) -> ConceptToken: """ Convert network output directly to concept token. This is useful for replacing discrete character selection in existing code. """ # Create a temporary generator just for conversion class DummyNetwork: pass class DummyProjection: pass generator = SoftThinkingGenerator(DummyNetwork(), encoder, DummyProjection(), top_k=top_k) return generator._output_to_concept_token(output) def concept_token_to_character(concept_token: ConceptToken, temperature: float = 0.8) -> str: """ Sample a character from a concept token. Convenience function for integration with existing code. """ return concept_token.sample_character(temperature)