Spaces:
Runtime error
Runtime error
Upload app.py with huggingface_hub
Browse files1 unmodified line2345678910111213141516173 unmodified lines212223242526272890 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014021 unmodified linefrom __future__ import annotationsfrom collections import dequefrom dataclasses import dataclassimport randomimport refrom typing import Dict, Iterable, List, Sequence, Tupleimport spaces # Must precede torch: ZeroGPU patches CUDA placement at import time.import torchfrom torch import nnimport torch.nn.functional as Fimport gradio as gr3 unmodified linesFACE_NAMES = ("U", "R", "F", "D", "L", "B")FACE_COLORS = ("#f5f5f5", "#dc2626", "#16a34a", "#facc15", "#f97316", "#2563eb")MOVES = tuple(move for face in FACE_NAMES for move in (face, f"{face}'"))MOVE_INDEX = {move: index for index, move in enumerate(MOVES)}INVERSE = {move: (move[:-1] if move.endswith("'") else f"{move}'") for move in MOVES}SOLVED: State = tuple(color for color in range(6) for _ in range(4))# Each face defines its outward normal plus its screen-right and screen-down axes.90 unmodified linesreturn scrambledef cube_svg(state: State) -> str:"""Render a compact 2D cube net without requiring image dependencies."""locations = {"U": (72, 0), "L": (0, 72), "F": (72, 72), "R": (144, 72), "B": (216, 72), "D": (72, 144)}pieces: List[str] = ["<svg viewBox='0 0 288 216' width='100%' role='img' aria-label='2 by 2 cube net'>"]for face_index, face in enumerate(FACE_NAMES):x0, y0 = locations[face]pieces.append(f"<text x='{x0 + 32}' y='{y0 + 11}' text-anchor='middle' font-size='10' fill='#475569'>{face}</text>")for sticker in range(4):row, col = divmod(sticker, 2)color = FACE_COLORS[state[face_index * 4 + sticker]]x, y = x0 + col * 32, y0 + 14 + row * 28pieces.append(f"<rect x='{x + 1}' y='{y + 1}' width='30' height='26' rx='3' fill='{color}' stroke='#0f172a' stroke-width='1.5'/>")pieces.append("</svg>")return "".join(pieces)def parse_state(text: str) -> Tuple[State | None, str]:"""Accept standard move notation or a 24-letter U/R/F/D/L/B sticker state."""cleaned = text.upper().replace("’", "'").strip()sticker_text = re.sub(r"[^URFDLB]", "", cleaned)if len(sticker_text) == 24 and len(cleaned.replace(" ", "").replace("\n", "").replace("\t", "")) == 24:if any(sticker_text.count(face) != 4 for face in FACE_NAMES):return None, "A sticker state must contain exactly four of each U, R, F, D, L, and B letter."return tuple(FACE_NAMES.index(color) for color in sticker_text), "Loaded 24-sticker state."moves = cleaned.split()if not moves:return None, "Enter a scramble such as `R U F' R'`, or 24 sticker letters in U/R/F/D/L/B face order."if any(move not in MOVES for move in moves):return None, "Use only quarter turns U R F D L B and their primes, separated by spaces."return apply_moves(SOLVED, moves), f"Loaded scramble: {' '.join(moves)}"def state_tensor(states: Sequence[State], device: str) -> torch.Tensor:stickers = torch.tensor(states, dtype=torch.long, device=device)return F.one_hot(stickers, num_classes=6).float().flatten(start_dim=1)class CubeQNetwork(nn.Module):"""A compact local neural approximation Q(s, a) for the 12 cube actions."""def __init__(self) -> None:super().__init__()self.layers = nn.Sequential(nn.Linear(144, 192), nn.ReLU(),nn.Linear(192, 192), nn.ReLU(),nn.Linear(192, len(MOVES)),)def forward(self, state: torch.Tensor) -> torch.Tensor:return self.layers(state)# ZeroGPU packs this read-only template at startup. Per-session weights are carried# through gr.State so independently trained visitors never mutate global state.BASE_MODEL = CubeQNetwork().to("cuda").eval()def new_session_weights() -> Dict[str, torch.Tensor]:return {name: value.detach().cpu().clone() for name, value in BASE_MODEL.state_dict().items()}def load_session_model(weights: Dict[str, torch.Tensor] | None) -> CubeQNetwork:model = CubeQNetwork().to("cuda")model.load_state_dict(weights or new_session_weights())return modeldef reverse_scramble_transitions(episodes: int, max_depth: int, seed: int) -> Tuple[List[State], List[int], List[float], List[State]]:rng = random.Random(seed)states: List[State] = []actions: List[int] = []rewards: List[float] = []next_states: List[State] = []for _ in range(episodes):scramble = random_scramble(rng.randint(1, max_depth), rng)state = apply_moves(SOLVED, scramble)for action in (INVERSE[move] for move in reversed(scramble)):successor = apply_move(state, action)states.append(state)actions.append(MOVE_INDEX[action])rewards.append(1.0 if successor == SOLVED else 0.0)next_states.append(successor)state = successorreturn states, actions, rewards, next_states@spaces.GPU(duration=45)def train_local_model(weights: Dict[str, torch.Tensor] | None,episodes: int,max_depth: int,epochs: int,seed: int,) -> Tuple[Dict[str, torch.Tensor], str]:"""Train this session's neural Q-network from reverse-scramble RL episodes."""torch.manual_seed(int(seed))model = load_session_model(weights).train()states, actions, rewards, next_states = reverse_scramble_transitions(int(episodes), int(max_depth), int(seed))state_batch = state_tensor(states, "cuda")next_batch = state_tensor(next_states, "cuda")action_batch = torch.tensor(actions, dtype=torch.long, device="cuda")reward_batch = torch.tensor(rewards, dtype=torch.float32, device="cuda")optimizer = torch.optim.AdamW(model.parameters(), lr=0.0015, weight_decay=0.0001)losses = []batch_size = min(512, len(states))for _ in range(int(epochs)):order = torch.randperm(len(states), device="cuda")for indices in order.split(batch_size):q_values = model(state_batch[indices]).gather(1, action_batch[indices, None]).squeeze(1)with torch.no_grad():targets = reward_batch[indices] + 0.92 * (reward_batch[indices] == 0).float() * model(next_batch[indices]).max(dim=1).valuesloss = F.smooth_l1_loss(q_values, targets)optimizer.zero_grad(set_to_none=True)loss.backward()torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)optimizer.step()losses.append(loss.item())saved_weights = {name: value.detach().cpu() for name, value in model.eval().state_dict().items()}return saved_weights, (f"Trained this session's local neural Q-network on **{len(states):,}** reverse-scramble transitions "f"({int(episodes):,} episodes, depths 1-{int(max_depth)}, {int(epochs)} passes). Final Huber loss: **{losses[-1]:.4f}**.")def policy_rollout(model: CubeQNetwork, state: State, maximum_steps: int) -> Tuple[List[str], bool]:moves: List[str] = []visited = {state}previous_face = ""with torch.no_grad():for _ in range(maximum_steps):if state == SOLVED:return moves, Truevalues = model(state_tensor([state], "cuda"))[0].tolist()ranked = sorted(range(len(MOVES)), key=lambda index: values[index], reverse=True)action_index = next((index for index in ranked if MOVES[index][0] != previous_face), ranked[0])move = MOVES[action_index]state = apply_move(state, move)moves.append(move)if state in visited:return moves, Falsevisited.add(state)previous_face = move[0]return moves, state == SOLVEDdef bidirectional_solution(start: State, max_depth: int = 12) -> List[str] | None:"""Find an exact shallow solution only when the explicitly labelled fallback is enabled."""if start == SOLVED:return []forward, backward = {start: []}, {SOLVED: []}forward_frontier, backward_frontier = [start], [SOLVED]def expand(frontier: List[State], seen: Dict[State, List[str]], other: Dict[State, List[str]], from_start: bool) -> Tuple[List[State], List[str] | None]:next_frontier: List[State] = []for state in frontier:path = seen[state]last_face = path[-1][0] if path else ""for move in MOVES:if move[0] == last_face:continuesuccessor = apply_move(state, move)if successor in seen:continuecandidate = path + [move]if successor in other:if from_start:return next_frontier, candidate + [INVERSE[item] for item in reversed(other[successor])]return next_frontier, other[successor] + [INVERSE[item] for item in reversed(candidate)]seen[successor] = candidatenext_frontier.append(successor)return next_frontier, Nonefor _ in range(max_depth):if len(forward_frontier) <= len(backward_frontier):forward_frontier, solution = expand(forward_frontier, forward, backward, True)else:backward_frontier, solution = expand(backward_frontier, backward, forward, False)if solution is not None:return solutionif not forward_frontier or not backward_frontier:breakreturn None@spaces.GPU(duration=20)def solve_user_state(weights: Dict[str, torch.Tensor] | None,encoded_state: List[int],maximum_steps: int,use_fallback: bool,) -> Tuple[str, str, str]:"""Use the session's trained neural Q-policy to solve a supplied 2x2x2 cube state."""state = tuple(encoded_state)model = load_session_model(weights).eval()learned_moves, solved = policy_rollout(model, state, int(maximum_steps))final_state = apply_moves(state, learned_moves)lines = [f"Neural Q-policy rollout: `{' '.join(learned_moves) or '(already solved)'}`"]mode = "learned neural policy"if not solved and use_fallback:fallback = bidirectional_solution(final_state)if fallback is not None:final_state = apply_moves(final_state, fallback)learned_moves.extend(fallback)lines.append(f"Exact fallback after the neural rollout: `{' '.join(fallback) or '(already solved)'}`")mode = "neural policy + exact fallback"else:lines.append("The exact fallback reached its depth limit. Try a state made from a shorter scramble.")solved = final_state == SOLVEDlines.append(f"Result: **{'solved' if solved else 'not solved'}** with {mode} in {len(learned_moves)} moves.")return cube_svg(final_state), "\n\n".join(lines), " ".join(learned_moves)def load_user_input(text: str) -> Tuple[str, List[int] | None, str]:"""Parse a user-supplied cube scramble or sticker state for the ZeroGPU solver."""state, message = parse_state(text)if state is None:return cube_svg(SOLVED), None, f"**Input error:** {message}"return cube_svg(state), list(state), messagedef make_random_problem(length: int, seed: int) -> Tuple[str, str, List[int], str]:"""Generate a reproducible random scramble to train and test the local model."""scramble = random_scramble(int(length), random.Random(int(seed)))state = apply_moves(SOLVED, scramble)return cube_svg(state), " ".join(scramble), list(state), "Random state loaded."with gr.Blocks(title="ZeroGPU Cube Q-Learning Lab") as demo:session_weights = gr.State(value=None)current_state = gr.State(value=list(SOLVED))gr.Markdown("# ZeroGPU Cube Q-Learning Lab\n""Train a **local neural Q-network** for your browser session on reverse-scramble reinforcement-learning episodes, then use it on a cube state you supply. ""Training and inference run in `@spaces.GPU` ZeroGPU workers; the model weights return to session state between clicks.")with gr.Row():with gr.Column():gr.Markdown("### 1. Train your local model")episodes = gr.Slider(500, 20000, value=6000, step=500, label="RL episodes")train_depth = gr.Slider(2, 10, value=7, step=1, label="Maximum training scramble depth")epochs = gr.Slider(1, 8, value=3, step=1, label="Fitted-Q passes")train_seed = gr.Number(value=19, precision=0, label="Training seed")train_button = gr.Button("Train session Q-network", variant="primary")training_report = gr.Markdown("No model trained in this session yet.")with gr.Column():gr.Markdown("### 2. Give the solver a cube state")state_input = gr.Textbox(label="Scramble or 24-sticker state",placeholder="R U F' R' or UUUURRRRFFFFDDDDLLLLBBBB",lines=2,)load_button = gr.Button("Load supplied state")random_length = gr.Slider(1, 12, value=7, step=1, label="Random scramble length")random_seed = gr.Number(value=42, precision=0, label="Random scramble seed")random_button = gr.Button("Generate random state")with gr.Row():cube = gr.HTML(cube_svg(SOLVED), label="Cube state")with gr.Column():input_report = gr.Markdown("Load a scramble, a sticker state, or generate a random problem.")rollout_steps = gr.Slider(1, 18, value=12, step=1, label="Maximum neural-policy steps")fallback = gr.Checkbox(value=True, label="Use exact bidirectional fallback if the neural policy does not finish")solve_button = gr.Button("Run trained model", variant="primary")solution_report = gr.Markdown("The model's rollout will appear here.")solution_moves = gr.Textbox(label="Moves applied", interactive=False)gr.Examples(examples=[["R U F' R'"], ["U R F U' L B'"], ["UUUURRRRFFFFDDDDLLLLBBBB"]],inputs=[state_input],outputs=[cube, current_state, input_report],fn=load_user_input,cache_examples=True,cache_mode="lazy",label="Input examples",)train_button.click(train_local_model, inputs=[session_weights, episodes, train_depth, epochs, train_seed], outputs=[session_weights, training_report])load_button.click(load_user_input, inputs=state_input, outputs=[cube, current_state, input_report])random_button.click(make_random_problem, inputs=[random_length, random_seed], outputs=[cube, state_input, current_state, input_report])solve_button.click(solve_user_state, inputs=[session_weights, current_state, rollout_steps, fallback], outputs=[cube, solution_report, solution_moves])if __name__ == "__main__":1 unmodified line23456789103 unmodified lines14151617181990 unmodified lines1101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142151 unmodified linefrom __future__ import annotationsimport randomfrom typing import Iterable, List, Tupleimport gradio as gr3 unmodified linesFACE_NAMES = ("U", "R", "F", "D", "L", "B")FACE_COLORS = ("#f5f5f5", "#dc2626", "#16a34a", "#facc15", "#f97316", "#2563eb")MOVES = tuple(move for face in FACE_NAMES for move in (face, f"{face}'"))SOLVED: State = tuple(color for color in range(6) for _ in range(4))# Each face defines its outward normal plus its screen-right and screen-down axes.90 unmodified linesreturn scrambledef cube_preview(state: State) -> str:"""Render a CSS-only, rotatable 3D cube preview for the supplied sequence."""faces = []for face_index, face in enumerate(FACE_NAMES):stickers = "".join(f"<span style='background:{FACE_COLORS[state[face_index * 4 + sticker]]}'></span>"for sticker in range(4))faces.append(f"<div class='cube-face cube-{face.lower()}'>{stickers}</div>")return """<style>.cube-stage { min-height: 310px; display: grid; place-items: center; perspective: 720px; overflow: hidden; }.cube-3d { width: 160px; height: 160px; position: relative; transform-style: preserve-3d; transform: rotateX(-25deg) rotateY(38deg); animation: cube-float 5s ease-in-out infinite; }.cube-face { position: absolute; width: 160px; height: 160px; display: grid; grid-template-columns: repeat(2, 1fr); gap: 5px; padding: 5px; box-sizing: border-box; background: #0f172a; border: 2px solid #020617; backface-visibility: hidden; }.cube-face span { border-radius: 5px; border: 1px solid rgba(15, 23, 42, .8); box-shadow: inset 0 0 10px rgba(255, 255, 255, .22); }.cube-f { transform: translateZ(80px); } .cube-b { transform: rotateY(180deg) translateZ(80px); }.cube-r { transform: rotateY(90deg) translateZ(80px); } .cube-l { transform: rotateY(-90deg) translateZ(80px); }.cube-u { transform: rotateX(90deg) translateZ(80px); } .cube-d { transform: rotateX(-90deg) translateZ(80px); }@keyframes cube-float { 50% { transform: rotateX(-19deg) rotateY(58deg) translateY(-7px); } }</style><div class='cube-stage' role='img' aria-label='Interactive-style 3D 2 by 2 cube preview'><div class='cube-3d'>%s</div></div>""" % "".join(faces)def parse_sequence(text: str) -> Tuple[List[str] | None, str]:"""Normalize a quarter-turn sequence for preview and model inference."""sequence = text.upper().replace("’", "'").replace(",", " ").split()if not sequence:return None, "Enter a sequence such as `R U F' R'`, or generate one below."invalid = [move for move in sequence if move not in MOVES]if invalid:return None, "Use quarter turns U, R, F, D, L, B and optional primes, separated by spaces."return sequence, "Initial state ready for deployed-model inference."def load_user_input(text: str) -> Tuple[str, str, str]:"""Apply a supplied sequence and show its 3D initial-state preview."""sequence, message = parse_sequence(text)if sequence is None:return cube_preview(SOLVED), text, messagenormalized = " ".join(sequence)return cube_preview(apply_moves(SOLVED, sequence)), normalized, messagedef make_random_problem(length: int, seed: int) -> Tuple[str, str, str]:"""Generate a random legal turn sequence and show its 3D initial state."""scramble = random_scramble(int(length), random.Random(int(seed)))sequence = " ".join(scramble)return cube_preview(apply_moves(SOLVED, scramble)), sequence, "Random initial state ready for deployed-model inference."def solve_with_deployed_model(initial_state: str) -> str:"""Reserve the inference endpoint for the pretrained 2x2x2 cube model."""sequence, message = parse_sequence(initial_state)if sequence is None:return messagereturn "Model checkpoint pending: this input is ready for deployed-model inference once the trained artifact is added."with gr.Blocks(title="ZeroGPU Cube Q-Learning Lab") as demo:gr.Markdown("# ZeroGPU Cube Q-Learning Lab\n""Provide an initial 2x2x2 cube state and ask a deployed local model for a solution. ""Training happens outside this website; this Space is inference-only.")with gr.Row():with gr.Column():gr.Markdown("### Initial state")state_input = gr.Textbox(label="Initial turn sequence",placeholder="R U F' R'",lines=2,)load_button = gr.Button("Save initial state")random_length = gr.Slider(1, 12, value=7, step=1, label="Random scramble length")random_seed = gr.Number(value=42, precision=0, label="Random scramble seed")random_button = gr.Button("Generate random initial state")input_report = gr.Markdown("Enter the initial state that the deployed model should solve.")with gr.Column():cube = gr.HTML(cube_preview(SOLVED), label="3D cube preview")gr.Markdown("### Model inference")model_status = gr.Markdown("**Model status:** checkpoint not yet included in this Space.")solve_button = gr.Button("Solve with deployed model", variant="primary")solution_report = gr.Markdown("The model solution will appear here.")solution_moves = gr.Textbox(label="Predicted solution moves", interactive=False)gr.Examples(examples=[["R U F' R'"], ["U R F U' L B'"], ["R' D L U' B F"]],inputs=[state_input],outputs=[cube, state_input, input_report],fn=load_user_input,cache_examples=True,cache_mode="lazy",label="Input examples",)load_button.click(load_user_input, inputs=state_input, outputs=[cube, state_input, input_report])random_button.click(make_random_problem, inputs=[random_length, random_seed], outputs=[cube, state_input, input_report])solve_button.click(solve_with_deployed_model, inputs=state_input, outputs=solution_report)if __name__ == "__main__":
app.py+75-262