Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-03c66d73-198a-4dbe-97c8-033faa017f891753179432483-2025_07_22-12.17.22.136/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-06f10f80-b6a2-425e-b27d-84918dea2c761762366776749-2025_11_05-19.19.45.476/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-07425894-b527-4190-aa05-52f7ce3502361763305561836-2025_11_16-16.06.50.327/source.csv +7 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-0772a0e5-c412-4c7f-baf8-baf5f41b5a071761919749757-2025_10_31-15.09.15.35/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-0b876cde-7995-4327-9784-8940a6f9a4611761909818675-2025_10_31-12.23.50.925/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-0f165f77-177d-4df8-8da6-833f9d4dc2621758655771904-2025_09_23-21.29.35.488/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-0f1e5d63-c4d1-4ee6-8f4b-f23571bb0c0c1758099534191-2025_09_17-10.59.01.455/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-15e0d6d5-3ae8-440c-b7a5-a1cb5029f9c91754397775073-2025_08_05-14.43.03.950/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-1f08d006-5137-4519-a573-243293d86d501755585788047-2025_08_19-08.43.15.93/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-21778a94-9825-4201-af99-89dfb6cb16761765132330802-2025_12_07-19.32.14.330/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-22c698ce-dba2-4474-8e3d-c49a8a8edd3f1761202197218-2025_10_23-08.50.06.406/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-29a8bb18-ba85-4426-b147-2ee7b78406511756538623430-2025_08_30-09.24.03.821/source.csv +6 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-29b02d56-00bb-4d54-ae16-3db6a9d130f81758358491962-2025_09_20-10.54.58.769/source.csv +37 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-2a9bf505-97e2-485f-ae8a-8a5d3e22aceb1753782197393-2025_07_29-11.43.57.848/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-2f5b13c7-61f7-4340-b581-9edac6a53f1f1753015255059-2025_07_20-14.41.09.478/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-2fa035c7-d6bc-4ff1-a7cc-4b06be2f31801763194882325-2025_11_15-09.21.29.317/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-3ff5af95-247c-4adc-870c-57d666851fef1762448563284-2025_11_06-18.02.48.472/source.csv +37 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-41b294b4-b89c-4c1d-8a02-14afc9168dc41753085667665-2025_07_21-10.15.04.628/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-423369b5-91d4-45bc-a235-e640891c4f971759246484029-2025_09_30-17.34.52.514/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-42ef4ad5-d074-4f54-bd5e-892223ecd60a1762276234813-2025_11_04-18.10.41.464/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-43cc33c5-d808-49c3-aea6-b65ee92239d91763660422797-2025_11_20-18.40.29.930/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-46704c60-57ef-4934-8ea5-e02f81167b881756236789102-2025_08_26-21.33.18.58/source.csv +95 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-46a4cc9d-ac37-44ff-ae8d-547db76d96f31752072213286-2025_07_09-16.43.57.848/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-4719c5f9-1b15-4792-8afd-690761108bda1751617825355-2025_07_04-10.31.22.581/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-48d8454e-eb9c-4d78-a257-1c3ae6fff0eb1767631180086-2026_01_05-17.39.46.786/source.csv +23 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-4bdfe74d-d330-4df6-b567-868d1f5d15041765303872322-2025_12_09-19.11.17.849/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-4c69dcf8-a147-4975-8e49-6c7ed4761fb81758276984897-2025_09_19-12.16.27.253/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-4dca7453-99f2-409f-9fcb-ea8ac3cd34081767515723494-2026_01_04-15.57.54.263/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-5051ecd3-3076-430b-bdb2-8f2670bf437e1764846717687-2025_12_04-12.12.06.33/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-517cf587-dd37-4da1-93e0-2dbe2eb778af1759393261841-2025_10_02-10.21.12.61/source.csv +217 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-53d91009-6945-47d9-96a4-938a0ca5e66c1758023129511-2025_09_16-13.45.36.509/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-5bd2220b-fd06-4957-ae02-02d699413f701762612130038-2025_11_08-15.28.56.621/source.csv +85 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-5f48c907-14e5-4011-960f-0c7da6e16d1c1755864806800-2025_08_22-14.13.40.52/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-6061119e-3f80-4137-8240-2452a9d7dd541755784835236-2025_08_21-16.00.55.612/source.csv +12 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-61a8c6c4-3944-4cce-817c-d7f3d58f5a4d1764870580114-2025_12_04-18.49.46.89/source.csv +21 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-67216304-51bb-4456-bf20-d9a7d43f4abc1762614700573-2025_11_08-16.11.46.209/source.csv +145 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-67b923a6-2474-4a8c-924a-d100648f06ad1759141988418-2025_09_29-12.33.17.507/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-6848d624-e3ad-4152-9883-dc056cdeb99d1754923670198-2025_08_11-16.48.03.201/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-6a2b9de9-16b6-4ba2-9a19-eff03fad03561755414648588-2025_08_17-09.12.59.520/source.csv +201 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-6addbcf1-e348-4d74-b8dc-f84f47c305b71767631688034-2026_01_05-17.48.14.851/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-722d4ca4-d4cb-461b-8df1-6d561da0c5421759173367911-2025_09_29-21.16.13.607/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-72482fee-a24c-4c9f-bb09-3efbfa32b9fa1765978902238-2025_12_17-14.41.49.56/source.csv +4 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-752a7417-71d4-4957-9814-498a4313969f1763752672170-2025_11_21-20.18.00.979/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-75911912-40c4-4ec3-a711-47c0946a81a11767620334402-2026_01_05-14.39.02.36/source.csv +46 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-78105cc3-5fe0-4c79-a145-2a2fd28c2d411758789399345-2025_09_25-10.36.42.235/source.csv +244 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-7bef0c9e-0ef0-4ac6-8e84-5c42986c6b871756230969871-2025_08_26-19.57.46.431/source.csv +3 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-807b3b7b-c934-4e4b-a90d-2ec4fc057e6d1764325879483-2025_11_28-11.31.34.63/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-823236e5-d9b8-4c96-ab4a-24b8972648001754120306348-2025_08_02-09.38.34.668/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-82b7e9d3-cb7d-497a-bae7-ac831bb4275e1757959063865-2025_09_15-19.57.49.653/source.csv +0 -0
- 1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-83ba4202-5f73-4c54-861d-29dc5e6fd6df1758801545463-2025_09_25-13.59.28.362/source.csv +0 -0
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-03c66d73-198a-4dbe-97c8-033faa017f891753179432483-2025_07_22-12.17.22.136/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-06f10f80-b6a2-425e-b27d-84918dea2c761762366776749-2025_11_05-19.19.45.476/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-07425894-b527-4190-aa05-52f7ce3502361763305561836-2025_11_16-16.06.50.327/source.csv
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Sequence,Time,File,RangeOffset,RangeLength,Text,Language,Type
|
| 2 |
+
1,3,"crowd-pilot/crowd-pilot/serialization_utils.py",0,0,"#!/usr/bin/env python3\n""""""\nCommon utilities for dataset serialization scripts.\n""""""\n\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import List, Optional, Tuple, Dict\n\nimport difflib\nimport re\nimport pandas as pd\nfrom datasets import Dataset, load_dataset\n\n\n_ANSI_CSI_RE = re.compile(r""\x1b\[[0-9;?]*[ -/]*[@-~]"")\n_ANSI_OSC_TERMINATED_RE = re.compile(r""\x1b\][\s\S]*?(?:\x07|\x1b\\)"")\n_ANSI_OSC_LINE_FALLBACK_RE = re.compile(r""\x1b\][^\n]*$"")\n_BRACKETED_PASTE_ENABLE = ""\x1b[?2004h""\n_BRACKETED_PASTE_DISABLE = ""\x1b[?2004l""\n_OSC_633 = ""\x1b]633;""\n_OSC_0 = ""\x1b]0;""\n\n\n@dataclass\nclass SerializeConfig:\n output_dir: str\n shard_size: int\n target_chars: int\n overlap_chars: int\n min_session_chars: int\n max_docs: Optional[int]\n long_pause_threshold_ms: int\n csv_root: Optional[str]\n val_ratio: float\n arrayrecord_group_size: Optional[int] = None\n\n\ndef _clean_text(text: str) -> str:\n # Normalize line endings and strip trailing spaces; preserve tabs/newlines.\n return text.replace(""\r\n"", ""\n"").replace(""\r"", ""\n"").rstrip()\n\n\ndef _fenced_block(path: str, language: Optional[str], content: str) -> str:\n lang = (language or """").lower()\n return f""```{lang}\n{content}\n```\n""\n\n\ndef _apply_change(content: str, offset: int, length: int, new_text: str) -> str:\n # Mirrors crowd_code_player.replay_file.apply_change\n base = str(content)\n text = str(new_text) if pd.notna(new_text) else """"\n text = text.replace(""\\n"", ""\n"").replace(""\\r"", ""\r"")\n if offset > len(base):\n base = base + ("" "" * (offset - len(base)))\n return base[:offset] + text + base[offset + length:]\n\n\ndef _apply_backspaces(text: str) -> str:\n out: List[str] = []\n for ch in text:\n if ch == ""\b"": # \x08\n if out:\n out.pop()\n else:\n out.append(ch)\n return """".join(out)\n\n\ndef _normalize_terminal_output(raw: str) -> str:\n """"""\n Normalize PTY/terminal output for training:\n - Apply backspaces (\x08)\n - Strip OSC (window title/shell integration) first, keeping BEL/ST terminators intact\n - Resolve carriage returns (\r) by keeping the last rewrite per line\n - Strip CSI (coloring etc.)\n - Finally drop any remaining BEL (\x07)\n """"""\n if not raw:\n return raw\n s = _apply_backspaces(raw)\n # Remove OSC sequences that are properly terminated (BEL or ST)\n s = _ANSI_OSC_TERMINATED_RE.sub("""", s)\n # Fallback: drop any unterminated OSC up to end-of-line only\n s = ""\n"".join(_ANSI_OSC_LINE_FALLBACK_RE.sub("""", line) for line in s.split(""\n""))\n # Resolve carriage returns per line:\n # - If there are multiple rewrites, keep the last non-empty chunk\n # - If it's CRLF (ending with '\r' before '\n'), keep the content before '\r'\n resolved_lines: List[str] = []\n for seg in s.split(""\n""):\n parts = seg.split(""\r"")\n chosen = """"\n # pick last non-empty part if available; else last part\n for p in reversed(parts):\n if p != """":\n chosen = p\n break\n if chosen == """" and parts:\n chosen = parts[-1]\n resolved_lines.append(chosen)\n s = ""\n"".join(resolved_lines)\n # Strip ANSI escape sequences\n s = _ANSI_CSI_RE.sub("""", s)\n # Remove any remaining BEL beeps\n s = s.replace(""\x07"", """")\n return s\n\n\ndef _line_numbered_output(content: str, start_line: Optional[int] = None, end_line: Optional[int] = None) -> str:\n # FIXME (f.srambical): check whether this corresponds **exactly** to the output of cat -n {file_path} | sed -n '{vstart},{vend}p'\n lines = content.splitlines()\n total = len(lines)\n if total == 0:\n return """"\n s = 1 if start_line is None else max(1, min(start_line, total))\n e = total if end_line is None else max(1, min(end_line, total))\n assert e >= s, ""End line number cannot be less than start line number! Likely a bug in the line numbering computation.""\n buf: List[str] = []\n for idx in range(s, e + 1):\n buf.append(f""{idx:6}\t{lines[idx - 1]}"")\n return ""\n"".join(buf)\n\n\ndef _compute_viewport(total_lines: int, center_line: int, radius: int) -> Tuple[int, int]:\n if total_lines <= 0:\n return (1, 0)\n start = max(1, center_line - radius)\n end = min(total_lines, center_line + radius)\n assert end >= start, ""Viewport cannot have negative width! Likely a bug in the viewport computation.""\n return (start, end)\n\n\ndef _escape_single_quotes_for_sed(text: str) -> str:\n # Close quote, add an escaped single quote, reopen quote: '""'""'\n return text.replace(""'"", ""'\""'\""'"")\n\n\ndef _compute_changed_block_lines(\n before: str, after: str\n) -> Tuple[int, int, int, int, List[str]]:\n """"""\n Return 1-based start and end line numbers in 'before' that should be\n replaced, 1-based start and end line numbers in 'after' that contain\n the replacement, and the replacement lines from 'after'.\n\n For pure deletions, the replacement list may be empty.\n """"""\n before_lines = before.splitlines()\n after_lines = after.splitlines()\n sm = difflib.SequenceMatcher(a=before_lines, b=after_lines, autojunk=False)\n opcodes = [op for op in sm.get_opcodes() if op[0] != ""equal""]\n assert opcodes, ""Opcode list cannot be empty! Likely a bug in the diff computation.""\n\n first = opcodes[0]\n last = opcodes[-1]\n # i1/i2 refer to 'before' indices, j1/j2 to 'after'\n start_before = max(1, first[1] + 1)\n end_before = last[2] # no increment since we go from 'exclusive' to 'inclusive' indexing\n start_after = max(1, first[3] + 1)\n end_after = last[4]\n replacement_lines = after_lines[first[3] : last[4]]\n return (start_before, end_before, start_after, end_after, replacement_lines)\n\n\ndef _session_to_transcript(\n df: pd.DataFrame,\n long_pause_threshold_ms: int,\n) -> str:\n\n file_states: Dict[str, str] = {}\n terminal_state: str = """"\n per_file_event_counts: Dict[str, int] = {}\n per_file_cursor_positions: Dict[str, Tuple[int, int]] = {} # (offset, length) for each file\n last_time_ms: Optional[int] = None\n\n parts: List[str] = []\n\n for i in range(len(df)):\n row = df.iloc[i]\n file_path: str = row[""File""]\n event_time: int = row[""Time""]\n language: Optional[str] = row[""Language""]\n\n # Long pause detection\n if last_time_ms is not None:\n delta = event_time - last_time_ms\n if delta > long_pause_threshold_ms:\n # TODO (f.srambical): think about whether we want to emit this as an observation or not\n parts.append(f""<obs long_pause ms=\""{delta}\"" />"")\n last_time_ms = event_time\n\n event_type = row[""Type""]\n\n match event_type:\n case ""tab"":\n # File switch event\n parts.append(f""<act focus file=\""{file_path}\"" />"")\n \n # If Text is present, this is the first time opening the file\n # and the entire file content is captured\n text = row[""Text""]\n if pd.notna(text):\n file_content = str(text).replace(""\\n"", ""\n"").replace(""\\r"", ""\r"")\n file_states[file_path] = file_content\n parts.append(f""// observation: file={file_path}"")\n parts.append(_fenced_block(file_path, language, _clean_text(file_content)))\n\n case ""terminal_command"":\n # Terminal command execution\n command = row[""Text""]\n command_str = str(command).replace(""\\n"", ""\n"").replace(""\\r"", ""\r"")\n parts.append(f""<act terminal_command />"")\n parts.append(_fenced_block(file_path, ""bash"", _clean_text(command_str)))\n\n case ""terminal_output"":\n # Terminal output capture\n output = row[""Text""]\n output_str = str(output).replace(""\\n"", ""\n"").replace(""\\r"", ""\r"")\n parts.append(f""<obs terminal_output />"")\n parts.append(_fenced_block(file_path, None, _clean_text(output_str)))\n\n case ""terminal_focus"":\n # Terminal focus event\n parts.append(f""<act focus target=\""terminal\"" />"")\n\n case ""git_branch_checkout"":\n # Git branch checkout event\n branch_info = row[""Text""]\n branch_str = str(branch_info).replace(""\\n"", ""\n"").replace(""\\r"", ""\r"")\n parts.append(f""<act git_branch_checkout />"")\n parts.append(f""// git: {_clean_text(branch_str)}"")\n\n case ""selection_command"" | ""selection_mouse"" | ""selection_keyboard"":\n # Handle cursor movement\n offset = row[""RangeOffset""]\n length = row[""RangeLength""]\n old_cursor = per_file_cursor_positions.get(file_path, (0, 0))\n new_cursor = (offset, length)\n per_file_cursor_positions[file_path] = new_cursor\n \n # Emit cursor movement observation if position changed\n if old_cursor != new_cursor:\n parts.append(f""<act cursor file=\""{file_path}\"" offset=\""{offset}\"" len=\""{length}\"" />"")\n\n case ""content"":\n # Handle file edit events\n offset = row[""RangeOffset""]\n length = row[""RangeLength""]\n new_text = row[""Text""]\n new_text_str = str(new_text) if pd.notna(new_text) else """"\n\n operation = ""noop""\n if length == 0 and new_text_str:\n operation = ""insert""\n elif length > 0 and not new_text_str:\n operation = ""delete""\n elif length > 0 and new_text_str:\n operation = ""replace""\n\n parts.append(f""<act {operation} file=\""{file_path}\"" offset=\""{offset}\"" len=\""{length}\"" />"")\n\n if new_text_str and (operation == ""insert"" or operation == ""replace""):\n parts.append(_fenced_block(file_path, language, _clean_text(new_text_str)))\n\n before = file_states.get(file_path, """")\n after = _apply_change(before, offset, length, new_text)\n file_states[file_path] = after\n per_file_event_counts[file_path] = per_file_event_counts.get(file_path, 0) + 1\n\n # Update cursor position after edit (cursor moves to end of inserted/replaced text)\n per_file_cursor_positions[file_path] = (offset + len(new_text_str), 0)\n\n case _:\n raise ValueError(f""Unknown event type: {event_type}"")\n\n return ""\n"".join(parts).strip()\n\n\ndef session_to_bash_formatted_transcript(\n df: pd.DataFrame,\n viewport_radius: int = 10,\n normalize_terminal_output: bool = True,\n coalesce_radius: int = 5,\n) -> str:\n r""""""\n Serialize a session to a bash-like transcript comprised of:\n - Commands (bash fenced blocks): cat -n, sed -i 'S,Ec\...' && cat -n | sed -n 'VSTART,VENDp'\n - Outputs (<stdout>...</stdout>) that reflect the file state after each action\n Tracks per-file state and a per-file viewport. Viewport only shifts when selection moves out of bounds\n or when first initialized.\n """"""\n file_states: Dict[str, str] = {}\n per_file_viewport: Dict[str, Optional[Tuple[int, int]]] = {}\n\n parts: List[str] = []\n terminal_output_buffer: List[str] = []\n pending_edits_before: Dict[str, Optional[str]] = {}\n pending_edit_regions: Dict[str, Optional[Tuple[int, int]]] = {}\n\n def _flush_terminal_output_buffer() -> None:\n if not terminal_output_buffer:\n return\n aggregated = """".join(terminal_output_buffer)\n out = aggregated\n if normalize_terminal_output:\n out = _normalize_terminal_output(out)\n cleaned = _clean_text(out)\n if cleaned.strip():\n parts.append(f""<stdout>\n{cleaned}\n</stdout>"")\n terminal_output_buffer.clear()\n\n def _flush_pending_edit_for_file(target_file: str) -> None:\n before_snapshot = pending_edits_before.get(target_file)\n if before_snapshot is None:\n return\n after_state = file_states.get(target_file, """")\n if before_snapshot.rstrip(""\n"") == after_state.rstrip(""\n""):\n pending_edits_before[target_file] = None\n pending_edit_regions[target_file] = None\n return\n (\n start_before,\n end_before,\n start_after,\n end_after,\n repl_lines,\n ) = _compute_changed_block_lines(before_snapshot, after_state)\n before_total_lines = len(before_snapshot.splitlines())\n if end_before < start_before:\n escaped_lines = [_escape_single_quotes_for_sed(line) for line in repl_lines]\n sed_payload = ""\n"".join(escaped_lines)\n if start_before <= max(1, before_total_lines):\n sed_cmd = f""sed -i '{start_before}i\\\n{sed_payload}' {target_file}""\n else:\n sed_cmd = f""sed -i '$a\\\n{sed_payload}' {target_file}""\n elif not repl_lines:\n sed_cmd = f""sed -i '{start_before},{end_before}d' {target_file}""\n else:\n escaped_lines = [_escape_single_quotes_for_sed(line) for line in repl_lines]\n sed_payload = ""\n"".join(escaped_lines)\n sed_cmd = f""sed -i '{start_before},{end_before}c\\\n{sed_payload}' {target_file}""\n total_lines = len(after_state.splitlines())\n center = (start_after + end_after) // 2\n vp = _compute_viewport(total_lines, center, viewport_radius)\n per_file_viewport[target_file] = vp\n vstart, vend = vp\n chained_cmd = f""{sed_cmd} && cat -n {target_file} | sed -n '{vstart},{vend}p'""\n parts.append(_fenced_block(target_file, ""bash"", _clean_text(chained_cmd)))\n viewport_output = _line_numbered_output(after_state, vstart, vend)\n parts.append(f""<stdout>\n{viewport_output}\n</stdout>"")\n pending_edits_before[target_file] = None\n pending_edit_regions[target_file] = None\n\n def _flush_all_pending_edits() -> None:\n for fname in list(pending_edits_before.keys()):\n _flush_pending_edit_for_file(fname)\n\n for i in range(len(df)):\n row = df.iloc[i]\n file_path: str = row[""File""]\n event_type = row[""Type""]\n \n match event_type:\n case ""tab"":\n _flush_all_pending_edits()\n _flush_terminal_output_buffer()\n text = row[""Text""]\n if pd.notna(text):\n content = str(text).replace(""\\n"", ""\n"").replace(""\\r"", ""\r"")\n file_states[file_path] = content\n # First open with full file capture\n cmd = f""cat -n {file_path}""\n parts.append(_fenced_block(file_path, ""bash"", _clean_text(cmd)))\n output = _line_numbered_output(content)\n parts.append(f""<stdout>\n{output}\n</stdout>"")\n else:\n # File switch without content snapshot: show current viewport only\n content = file_states.get(file_path, """")\n total_lines = len(content.splitlines())\n vp = per_file_viewport.get(file_path)\n if not vp or vp[1] == 0:\n vp = _compute_viewport(total_lines, 1, viewport_radius)\n per_file_viewport[file_path] = vp\n if vp:\n vstart, vend = vp\n cmd = f""cat -n {file_path} | sed -n '{vstart},{vend}p'""\n parts.append(_fenced_block(file_path, ""bash"", _clean_text(cmd)))\n viewport_output = _line_numbered_output(content, vstart, vend)\n parts.append(f""<stdout>\n{viewport_output}\n</stdout>"")\n\n case ""content"":\n _flush_terminal_output_buffer()\n offset = int(row[""RangeOffset""])\n length = int(row[""RangeLength""])\n new_text = row[""Text""]\n before = file_states.get(file_path, """")\n # Approximate current edit region in line space\n new_text_str = str(new_text) if pd.notna(new_text) else """"\n start_line_current = before[:offset].count(""\n"") + 1\n deleted_chunk = before[offset:offset + length]\n lines_added = new_text_str.count(""\n"")\n lines_deleted = deleted_chunk.count(""\n"")\n region_start = start_line_current\n region_end = start_line_current + max(lines_added, lines_deleted, 0)\n # Flush pending edits if this edit is far from the pending region\n current_region = pending_edit_regions.get(file_path)\n if current_region is not None:\n rstart, rend = current_region\n if region_start < (rstart - coalesce_radius) or region_start > (rend + coalesce_radius):\n _flush_pending_edit_for_file(file_path)\n current_region = None\n after = _apply_change(before, offset, length, new_text)\n if pending_edits_before.get(file_path) is None:\n pending_edits_before[file_path] = before\n # Update/initialize region union\n if current_region is None:\n pending_edit_regions[file_path] = (region_start, max(region_start, region_end))\n else:\n rstart, rend = current_region\n pending_edit_regions[file_path] = (min(rstart, region_start), max(rend, region_end))\n file_states[file_path] = after\n\n case ""selection_command"" | ""selection_mouse"" | ""selection_keyboard"":\n # During an edit burst (pending edits), suppress flush and viewport emissions\n if pending_edits_before.get(file_path) is None:\n _flush_terminal_output_buffer()\n else:\n # Skip emitting viewport while edits are pending to avoid per-keystroke sed/cat spam\n continue\n offset = int(row[""RangeOffset""])\n content = file_states.get(file_path, """")\n total_lines = len(content.splitlines())\n target_line = content[:offset].count(""\n"") + 1\n vp = per_file_viewport.get(file_path)\n should_emit = False\n if not vp or vp[1] == 0:\n vp = _compute_viewport(total_lines, target_line, viewport_radius)\n per_file_viewport[file_path] = vp\n should_emit = True\n else:\n vstart, vend = vp\n if target_line < vstart or target_line > vend:\n vp = _compute_viewport(total_lines, target_line, viewport_radius)\n per_file_viewport[file_path] = vp\n should_emit = True\n if should_emit and vp:\n vstart, vend = vp\n cmd = f""cat -n {file_path} | sed -n '{vstart},{vend}p'""\n parts.append(_fenced_block(file_path, ""bash"", _clean_text(cmd)))\n viewport_output = _line_numbered_output(content, vstart, vend)\n parts.append(f""<stdout>\n{viewport_output}\n</stdout>"")\n\n case ""terminal_command"":\n _flush_all_pending_edits()\n _flush_terminal_output_buffer()\n command = row[""Text""]\n command_str = str(command).replace(""\\n"", ""\n"").replace(""\\r"", ""\r"")\n parts.append(_fenced_block(file_path, ""bash"", _clean_text(command_str)))\n\n case ""terminal_output"":\n output = row[""Text""]\n raw_output = str(output).replace(""\\n"", ""\n"").replace(""\\r"", ""\r"")\n terminal_output_buffer.append(raw_output)\n\n case ""terminal_focus"":\n _flush_all_pending_edits()\n _flush_terminal_output_buffer()\n # No-op for bash transcript; focus changes don't emit commands/output\n pass\n\n case ""git_branch_checkout"":\n _flush_all_pending_edits()\n _flush_terminal_output_buffer()\n branch_info = row[""Text""]\n branch_str = str(branch_info).replace(""\\n"", ""\n"").replace(""\\r"", ""\r"")\n cleaned = _clean_text(branch_str)\n m = re.search(r""to '([^']+)'"", cleaned)\n if not m:\n raise ValueError(f""Could not extract branch name from git checkout message: {cleaned}"")\n branch_name = m.group(1).strip()\n # Safe-quote branch if it contains special characters\n if re.search(r""[^A-Za-z0-9._/\\-]"", branch_name):\n branch_name = ""'"" + branch_name.replace(""'"", ""'\""'\""'"") + ""'""\n cmd = f""git checkout {branch_name}""\n parts.append(_fenced_block(file_path, ""bash"", _clean_text(cmd)))\n\n case _:\n raise ValueError(f""Unknown event type: {event_type}"")\n\n _flush_all_pending_edits()\n _flush_terminal_output_buffer()\n return ""\n"".join(parts).strip()\n\ndef load_hf_csv(hf_path: str, split: str) -> Dataset:\n loaded = load_dataset(hf_path, split=split)\n\n assert isinstance(loaded, Dataset), ""Expected a Dataset from load_dataset""\n return loaded\n\n\ndef _discover_local_sessions(root: Path) -> List[Path]:\n # Recursively find all CSV files\n paths: List[Path] = []\n for p in root.rglob(""*.csv""):\n if p.is_file():\n paths.append(p)\n paths.sort()\n return paths\n\n\ndef _chunk_text(text: str, target_chars: int, overlap_chars: int) -> List[str]:\n """"""Split a long text into overlapping chunks near target length.""""""\n if target_chars <= 0:\n return [text]\n n = len(text)\n if n <= target_chars:\n return [text]\n\n chunks: List[str] = []\n start = 0\n # Ensure sane overlap\n overlap = max(0, min(overlap_chars, target_chars // 2))\n while start < n:\n end_target = min(start + target_chars, n)\n if end_target < n:\n end = end_target\n else:\n end = n\n chunk = text[start:end].strip()\n chunks.append(chunk)\n if end == n:\n break\n # advance with overlap\n start = max(0, end - overlap)\n if start >= n:\n break\n return chunks\n\n\n",python,tab
|
| 3 |
+
2,1241,"TERMINAL",0,0,"bash",,terminal_focus
|
| 4 |
+
3,1743,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"4:06:50 PM [info] Activating crowd-code\n4:06:50 PM [info] Recording started\n4:06:50 PM [info] Initializing git provider using file system watchers...\n4:06:50 PM [info] Git repository found\n4:06:50 PM [info] Git provider initialized successfully\n4:06:51 PM [info] Initial git state: [object Object]\n",Log,tab
|
| 5 |
+
4,3865,"extension-output-pdoom-org.crowd-code-#1-crowd-code",39,0,"",Log,selection_mouse
|
| 6 |
+
5,4415,"crowd-pilot/crowd-pilot/serialization_utils.py",0,0,"",python,tab
|
| 7 |
+
6,5776,"TERMINAL",0,0,"bash",,terminal_focus
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-0772a0e5-c412-4c7f-baf8-baf5f41b5a071761919749757-2025_10_31-15.09.15.35/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-0b876cde-7995-4327-9784-8940a6f9a4611761909818675-2025_10_31-12.23.50.925/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-0f165f77-177d-4df8-8da6-833f9d4dc2621758655771904-2025_09_23-21.29.35.488/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-0f1e5d63-c4d1-4ee6-8f4b-f23571bb0c0c1758099534191-2025_09_17-10.59.01.455/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-15e0d6d5-3ae8-440c-b7a5-a1cb5029f9c91754397775073-2025_08_05-14.43.03.950/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-1f08d006-5137-4519-a573-243293d86d501755585788047-2025_08_19-08.43.15.93/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-21778a94-9825-4201-af99-89dfb6cb16761765132330802-2025_12_07-19.32.14.330/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-22c698ce-dba2-4474-8e3d-c49a8a8edd3f1761202197218-2025_10_23-08.50.06.406/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-29a8bb18-ba85-4426-b147-2ee7b78406511756538623430-2025_08_30-09.24.03.821/source.csv
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Sequence,Time,File,RangeOffset,RangeLength,Text,Language,Type
|
| 2 |
+
1,2,"MaxText/train.py",0,0,"# Copyright 2023–2025 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the ""License"");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an ""AS IS"" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# pylint: disable=g-bad-todo, abstract-method, consider-using-with\n""""""Training loop and Decoding of the model.""""""\n\n# Calling jax.device_count here prevents a ""TPU platform already registered"" error.\n# See github.com/google/maxtext/issues/20 for more\n\nfrom typing import Any, Sequence\nimport datetime\nimport functools\nimport os\n\nfrom absl import app\n\nimport numpy as np\n\nimport pathwaysutils # pylint: disable=unused-import\n\nimport tensorflow as tf\n\nimport jax\nimport jax.numpy as jnp\n\nfrom flax import linen as nn\nfrom flax.linen import partitioning as nn_partitioning\n\nfrom cloud_tpu_diagnostics import diagnostic\nfrom cloud_tpu_diagnostics.configuration import debug_configuration\nfrom cloud_tpu_diagnostics.configuration import diagnostic_configuration\nfrom cloud_tpu_diagnostics.configuration import stack_trace_configuration\n\nfrom MaxText import checkpointing\nfrom MaxText import exceptions\nfrom MaxText import max_logging\nfrom MaxText import max_utils\nfrom MaxText import maxtext_utils\nfrom MaxText import train_utils\nfrom MaxText import profiler\nfrom MaxText import pyconfig\nfrom MaxText.layers.multi_token_prediction import calculate_mtp_acceptance_rate, calculate_mtp_loss\nfrom MaxText.data_loader import DataLoader\nfrom MaxText.input_pipeline.input_pipeline_interface import create_data_iterator\nfrom MaxText.globals import EPS\nfrom MaxText.metric_logger import MetricLogger\nfrom MaxText.utils import gcs_utils\nfrom MaxText.utils.goodput_utils import (\n GoodputEvent,\n create_goodput_recorder,\n maybe_monitor_goodput,\n maybe_record_goodput,\n)\nfrom MaxText.vertex_tensorboard import VertexTensorboardManager\n# Placeholder: internal\n\nimport MaxText as mt\n# pylint: disable=too-many-positional-arguments\n\n\ndef validate_train_config(config):\n """"""Validates the configuration is set correctly for 'train.py'.""""""\n\n assert config.run_name, ""Erroring out, need a real run_name""\n if config.dataset_path and not config.dataset_path.startswith(""gs://""):\n max_logging.log(""WARNING: 'dataset_path' might be pointing your local file system"")\n if not config.base_output_directory.startswith(""gs://""):\n max_logging.log(""WARNING: 'base_output_directory' might be pointing your local file system"")\n assert config.steps > 0, ""You must set steps or learning_rate_schedule_steps to a positive integer.""\n\n if config.quantization in (""fp8"", ""nanoo_fp8""):\n # pylint: disable=line-too-long\n assert config.gradient_accumulation_steps == 1, (\n ""fp8 can't be used with gradient_accumulation_steps right now. Please use other quantization or set ""\n ""gradient_accumulation_steps to 1""\n )\n\n # Check if GPU Flash Attention is being used with sequence packing\n if config.attention == ""cudnn_flash_te"" and config.packing and config.dataset_type != ""synthetic"":\n raise ValueError(\n ""cudnn_flash_te only supports BSHD format. The THD (seq packing) support is going to be available in ""\n ""Transformer Engine 2.0 release. ""\n ""Please disable sequence packing (set packing=False) or use a different attention mechanism. ""\n ""With synthetic data, the format is not important as packing is not applied.""\n )\n\n\ndef get_first_step(state):\n return int(state.step)\n\n\n# -----------------------------------------------------------------------------\n# Top-level Functions\n# -----------------------------------------------------------------------------\n\n\ndef record_activation_metrics(output_metrics, intermediate_outputs, config):\n """"""Adds the activation metrics to the metrics dict""""""\n\n if config.scan_layers:\n metrics_dict = intermediate_outputs[""intermediates""][""decoder""][""decoder""]\n\n for layer_num in range(config.num_decoder_layers):\n output_metrics[""scalar""][f""activ_fraction_zero/layer_{layer_num:03d}""] = metrics_dict[""activation_fraction_zero""][\n 0\n ][layer_num]\n output_metrics[""scalar""][f""activ_mean/layer_{layer_num:03d}""] = metrics_dict[""activation_mean""][0][layer_num]\n output_metrics[""scalar""][f""activ_stdev/layer_{layer_num:03d}""] = metrics_dict[""activation_stdev""][0][layer_num]\n else:\n for layer_num in range(config.num_decoder_layers):\n layer = intermediate_outputs[""intermediates""][""decoder""][f""layers_{layer_num}""]\n output_metrics[""scalar""][f""activ_fraction_zero/layer_{layer_num:03d}""] = layer[""activation_fraction_zero""][0]\n output_metrics[""scalar""][f""activ_mean/layer_{layer_num:03d}""] = layer[""activation_mean""][0]\n output_metrics[""scalar""][f""activ_stdev/layer_{layer_num:03d}""] = layer[""activation_stdev""][0]\n\n\ndef _split_dpo_state(state):\n reference_params = state.params[""reference_params""]\n new_state = state.replace(params={k: v for k, v in state.params.items() if k != ""reference_params""})\n return new_state, reference_params\n\n\ndef _merge_dpo_state(state, reference_params):\n return state.replace(params=dict(state.params, reference_params=reference_params))\n\n\ndef dpo_loss_fn(model, config, data, dropout_rng, params, reference_params, is_train=True):\n """"""loss_fn for both train and eval.\n\n Args:\n model: A nn.Module\n config: Config of parameters\n data: Batch of data to apply to the model\n dropout_rng: A key to use to generate rng for dropout\n params: Model params\n is_train: True for train_step and False for eval_step\n\n Returns:\n loss: average loss\n aux: a dictionary including intermediate_outputs, total_loss, and total_weights\n """"""\n # inputs, targets, segments, positions = apply_args\n rng1, aqt_rng = jax.random.split(dropout_rng)\n\n # decimate proportion of data when per_device_batch_size<1\n if is_train:\n for k, v in data.items():\n data[k] = v[: config.micro_batch_size_to_train_on, :]\n\n # for DPO we don't support packed sequence (they shouldn't be present in the first place)\n data[""chosen_segmentation""] = (data[""chosen_segmentation""] == 1).astype(jnp.int32)\n data[""rejected_segmentation""] = (data[""rejected_segmentation""] == 1).astype(jnp.int32)\n data[""chosen_position""] = data[""chosen_position""] * (data[""chosen_segmentation""] == 1)\n data[""rejected_position""] = data[""rejected_position""] * (data[""rejected_segmentation""] == 1)\n\n # concatenated model and reference model forward pass\n inputs = jnp.concatenate([data[""chosen""], data[""rejected""]], 0)\n inputs_position = jnp.concatenate([data[""chosen_position""], data[""rejected_position""]], 0)\n inputs_segmentation = jnp.concatenate([data[""chosen_segmentation""], data[""rejected_segmentation""]], 0)\n\n logits, intermediate_outputs = model.apply(\n params,\n inputs,\n inputs_position,\n decoder_segment_ids=inputs_segmentation,\n enable_dropout=config.enable_dropout if is_train else False,\n rngs={""dropout"": rng1, ""params"": aqt_rng},\n mutable=""intermediates"",\n )\n ref_logits = model.apply(\n {""params"": reference_params},\n inputs,\n inputs_position,\n decoder_segment_ids=inputs_segmentation,\n enable_dropout=False,\n rngs={""dropout"": rng1, ""params"": aqt_rng},\n )\n ref_logits = jax.lax.stop_gradient(ref_logits)\n\n # extract token ids, segmentation and logits for chosen and rejected sequences\n chosen_ids = data[""chosen""][..., 1:]\n rejected_ids = data[""rejected""][..., 1:]\n chosen_segmentation = data[""chosen_segmentation""][..., 1:]\n rejected_segmentation = data[""rejected_segmentation""][..., 1:]\n n_logits = logits.shape[-3] // 2 # [B, S, E] - [batch, sequence, embedding/vocab]\n chosen_logits, rejected_logits = logits[:n_logits, :, :], logits[n_logits:, :, :] # [B, S, E], [B, S, E]\n # ^ [B, S, E], [B, S, E]\n chosen_ref_logits, rejected_ref_logits = ref_logits[:n_logits, :, :], ref_logits[n_logits:, :, :]\n\n # common subsequence and padding mask\n common_prefix_mask = jnp.cumsum(chosen_ids != rejected_ids, axis=-1) == 0 # [B, S]\n valid_seq_mask = (chosen_segmentation != 0) & (rejected_segmentation != 0) & ~common_prefix_mask # [B, S]\n\n # compute logratios from the sequence-reduced observed token log-probability\n chosen_logps_seq = jnp.take_along_axis( # [B, S]\n jax.nn.log_softmax(chosen_logits[..., :-1, :], axis=-1), chosen_ids[..., None], axis=-1\n )[..., 0]\n chosen_logps = jnp.sum(chosen_logps_seq * valid_seq_mask, axis=-1) # [B]\n chosen_ref_logps_seq = jnp.take_along_axis( # [B, S]\n jax.nn.log_softmax(chosen_ref_logits[..., :-1, :], axis=-1), chosen_ids[..., None], axis=-1\n )[..., 0]\n chosen_ref_logps = jnp.sum(chosen_ref_logps_seq * valid_seq_mask, axis=-1) # [B]\n chosen_logratios = chosen_logps - chosen_ref_logps # [B]\n\n rejected_logps_seq = jnp.take_along_axis( # [B, S]\n jax.nn.log_softmax(rejected_logits[..., :-1, :], axis=-1), rejected_ids[..., None], axis=-1\n )[..., 0]\n rejected_logps = jnp.sum(rejected_logps_seq * valid_seq_mask, axis=-1) # [B]\n rejected_ref_logps_seq = jnp.take_along_axis( # [B, S]\n jax.nn.log_softmax(rejected_ref_logits[..., :-1, :], axis=-1), rejected_ids[..., None], axis=-1\n )[..., 0]\n rejected_ref_logps = jnp.sum(rejected_ref_logps_seq * valid_seq_mask, axis=-1) # [B]\n rejected_logratios = rejected_logps - rejected_ref_logps # [B]\n\n # DPO loss from chosen and rejected logratios\n LABEL_SMOOTHING, BETA = config.dpo_label_smoothing, config.dpo_beta\n logratios_delta = BETA * (chosen_logratios - rejected_logratios) # [B]\n losses = ( # [B]\n -jax.nn.log_sigmoid(BETA * logratios_delta) * (1 - LABEL_SMOOTHING)\n - jax.nn.log_sigmoid(-BETA * logratios_delta) * LABEL_SMOOTHING\n )\n total_loss, total_weights = jnp.mean(losses), losses.shape[0]\n loss = total_loss\n\n moe_lb_loss = 0.0\n if config.num_experts > 1:\n nested_key = (""intermediates"", ""decoder"", ""layers"", ""moe_lb_loss"")\n total_moe_lb_loss = maxtext_utils.get_nested_value(intermediate_outputs, nested_key, 0.0)\n moe_lb_loss = jnp.mean(jnp.array(total_moe_lb_loss))\n loss += moe_lb_loss\n reward_accuracy = jnp.mean(chosen_logratios > rejected_logratios)\n aux = {\n ""intermediate_outputs"": intermediate_outputs,\n ""total_loss"": total_loss,\n ""total_weights"": total_weights,\n ""moe_lb_loss"": moe_lb_loss,\n ""reward_accuracy"": reward_accuracy,\n }\n return loss, aux\n\n\ndef loss_fn(model, config, data, dropout_rng, params, is_train=True):\n """"""loss_fn for both train and eval.\n\n Args:\n model: A nn.Module\n config: Config of parameters\n data: Batch of data to apply to the model\n dropout_rng: A key to use to generate rng for dropout\n params: Model params\n is_train: True for train_step and False for eval_step\n\n Returns:\n loss: average loss\n aux: a dictionary including intermediate_outputs, total_loss, and total_weights\n """"""\n # inputs, targets, segments, positions = apply_args\n rng1, aqt_rng = jax.random.split(dropout_rng)\n\n # decimate proportion of data when per_device_batch_size<1\n if is_train:\n for k, v in data.items():\n data[k] = v[: config.micro_batch_size_to_train_on, :]\n else:\n for k, v in data.items():\n data[k] = v[: config.micro_batch_size_to_eval_on, :]\n mutable_collections = [""intermediates""]\n if config.mtp_num_layers > 0 and is_train:\n # The single model.apply call now triggers the entire chain if MTP is enabled:\n # Decoder runs -> returns hidden_state -> MTPBlock uses it -> MTPBlock sows losses -> we reap them here.\n mutable_collections.append(""mtp_losses"")\n\n # During evaluation, if the acceptance rate test is enabled, we must\n # make its specific collection mutable so the MTPBlock can sow into it.\n if config.mtp_eval_target_module > 0 and not is_train:\n mutable_collections.append(""mtp_acceptance"")\n\n logits, intermediate_outputs = model.apply(\n params,\n data[""inputs""],\n data[""inputs_position""],\n decoder_segment_ids=data[""inputs_segmentation""],\n encoder_images=data[""images""] if config.use_multimodal else None,\n enable_dropout=config.enable_dropout if is_train else False,\n rngs={""dropout"": rng1, ""params"": aqt_rng},\n mutable=mutable_collections,\n decoder_target_tokens=data[""targets""],\n decoder_target_mask=data[""targets_segmentation""],\n )\n one_hot_targets = jax.nn.one_hot(data[""targets""], config.vocab_size)\n xent, _ = max_utils.cross_entropy_with_logits(logits, one_hot_targets, 0.0)\n xent = nn.with_logical_constraint(xent, (""activation_embed_and_logits_batch"", ""activation_length""))\n # Mask out paddings at the end of each example.\n xent = xent * (data[""targets_segmentation""] != 0)\n total_loss = jnp.sum(xent)\n total_weights = jnp.sum(data[""targets_segmentation""] != 0)\n\n # If gradient accumulation is enabled, we don't need to divide total_loss\n # by total_weights and then multiply the computed gradient by total_weights,\n # since it's equivalent to computing the gradient from total_loss.\n # This simplification reduces the number of operations and makes it easier\n # for XLA to move all-reduce out of the gradient accumulation loop when use\n # Zero1+GA to reduce communication overhead.\n # EPS was used to avoid division by zero, but it's not needed when gradient\n # accumulation is enabled since there's no division.\n if config.gradient_accumulation_steps > 1:\n loss = total_loss\n else:\n loss = total_loss / (total_weights + EPS)\n\n # Calculate and Add MTP Loss\n mtp_loss = 0.0\n if config.mtp_num_layers > 0 and is_train:\n mtp_loss = calculate_mtp_loss(intermediate_outputs, config)\n loss += mtp_loss\n\n # get moe load balance loss\n moe_lb_loss = 0.0\n if config.num_experts > 1:\n nested_key = (""intermediates"", ""decoder"", ""layers"", ""moe_lb_loss"")\n total_moe_lb_loss = maxtext_utils.get_nested_value(intermediate_outputs, nested_key, 0.0)\n moe_lb_loss = jnp.mean(jnp.array(total_moe_lb_loss))\n loss += moe_lb_loss\n\n # Add the model's primary output to the intermediates dict so it can be used\n # by the acceptance rate calculation in eval_step.\n intermediate_outputs[""logits""] = logits\n\n aux = {\n ""intermediate_outputs"": intermediate_outputs,\n ""total_loss"": total_loss,\n ""total_weights"": total_weights,\n ""moe_lb_loss"": moe_lb_loss,\n ""mtp_loss"": mtp_loss,\n }\n return loss, aux\n\n\ndef train_step(model, config, state_mesh_shardings, state, data, dropout_rng):\n """"""\n\n Args:\n model: A nn.Module\n state: A pytree of the current state of the model\n data: Batch of data to apply to the model\n dropout_rng: A key to use to generate rng for dropout\n\n Returns:\n new_state: Same format as state.\n metrics: Dictionary of model metrics such as loss, training rate, etc.\n rng2: A new rng key that can be used in future calls.\n\n """"""\n reference_params, reference_params_sharding, extra_dpo_args, _loss_fn = [], [], [], loss_fn\n if config.use_dpo:\n state, reference_params = _split_dpo_state(state)\n state_mesh_shardings, reference_params_sharding = _split_dpo_state(state_mesh_shardings)\n extra_dpo_args = [reference_params]\n _loss_fn = dpo_loss_fn\n\n if config.gradient_accumulation_steps > 1:\n\n def accumulate_gradient(acc_grad_and_loss, data):\n grad_func = jax.value_and_grad(_loss_fn, argnums=4, has_aux=True)\n (_, aux), cur_batch_gradient = grad_func(\n model, config, data, dropout_rng, state.params, *extra_dpo_args, is_train=True\n )\n acc_grad_and_loss[""loss""] += aux[""total_loss""]\n acc_grad_and_loss[""moe_lb_loss""] += aux[""moe_lb_loss""]\n acc_grad_and_loss[""mtp_loss""] += aux[""mtp_loss""]\n acc_grad_and_loss[""grad""] = jax.tree_util.tree_map(\n lambda x, y: x + y, cur_batch_gradient, acc_grad_and_loss[""grad""]\n )\n acc_grad_and_loss[""total_weights""] += aux[""total_weights""]\n return acc_grad_and_loss, aux\n\n def reshape_to_microbatch_accumulations(batch_arr):\n """"""Reshape global batch to microbatches, assuming batch axis is leading.""""""\n microbatches = config.gradient_accumulation_steps\n microbatch_shape = (microbatches, batch_arr.shape[0] // microbatches) + batch_arr.shape[1:]\n return jnp.reshape(batch_arr, microbatch_shape)\n\n data = jax.tree_util.tree_map(reshape_to_microbatch_accumulations, data)\n init_grad = jax.tree_util.tree_map(jnp.zeros_like, state.params)\n init_grad_and_loss = {""loss"": 0.0, ""grad"": init_grad, ""total_weights"": 0, ""moe_lb_loss"": 0.0, ""mtp_loss"": 0.0}\n\n grad_and_loss, aux = jax.lax.scan(\n accumulate_gradient, init_grad_and_loss, data, length=config.gradient_accumulation_steps\n )\n loss = (\n grad_and_loss[""loss""] / grad_and_loss[""total_weights""]\n + grad_and_loss[""moe_lb_loss""] / config.gradient_accumulation_steps\n + grad_and_loss[""mtp_loss""] / config.gradient_accumulation_steps\n )\n raw_grads = jax.tree_util.tree_map(lambda arr: arr / grad_and_loss[""total_weights""], grad_and_loss[""grad""])\n aux = jax.tree.map(lambda x: jnp.sum(x, axis=0), aux) # pytype: disable=module-attr\n else:\n if config.optimizer_memory_host_offload:\n if config.use_dpo:\n reference_params = jax.device_put(\n reference_params, max_utils.with_memory_kind(reference_params_sharding, ""device"")\n )\n extra_dpo_args = [reference_params]\n grad_func = jax.value_and_grad(_loss_fn, argnums=4, has_aux=True)\n (loss, aux), raw_grads = grad_func(model, config, data, dropout_rng, state.params, *extra_dpo_args, is_train=True)\n intermediate_outputs = aux[""intermediate_outputs""]\n total_weights = aux[""total_weights""]\n moe_lb_loss = aux[""moe_lb_loss""]\n mtp_loss = aux[""mtp_loss""]\n\n if config.gradient_clipping_threshold > 0:\n grads = maxtext_utils.apply_gradient_clipping(raw_grads, state, config.gradient_clipping_threshold)\n else:\n grads = raw_grads\n if config.optimizer_memory_host_offload:\n state = state.replace(\n opt_state=jax.device_put(\n state.opt_state,\n jax.tree_util.tree_map(lambda x: x.with_memory_kind(kind=""device""), state_mesh_shardings.opt_state),\n )\n )\n # Move all parameters to device before optimizer update\n if config.parameter_memory_host_offload:\n max_logging.log(""\nMoving all parameters to device before optimizer update"")\n\n def move(path, value):\n max_logging.log(f""train.py: Moving f{path} to device"")\n return value.with_memory_kind(kind=""device"")\n\n state = state.replace(\n params=jax.device_put(\n state.params,\n jax.tree_util.tree_map_with_path(move, state_mesh_shardings.params),\n )\n )\n new_state = state.apply_gradients(grads=grads)\n\n scalar_metrics = {\n ""learning/loss"": loss,\n ""learning/moe_lb_loss"": moe_lb_loss,\n ""learning/mtp_loss"": mtp_loss,\n ""learning/total_weights"": total_weights,\n }\n if not config.optimizer_memory_host_offload:\n scalar_metrics[""learning/grad_norm""] = max_utils.l2norm_pytree(grads)\n scalar_metrics[""learning/raw_grad_norm""] = max_utils.l2norm_pytree(raw_grads)\n scalar_metrics[""learning/param_norm""] = max_utils.l2norm_pytree(new_state.params)\n if config.use_dpo:\n scalar_metrics[""learning/dpo_reward_accuracy""] = aux[""reward_accuracy""]\n metrics = {\n ""scalar"": scalar_metrics,\n ""scalars"": {},\n }\n\n if config.record_internal_nn_metrics:\n record_activation_metrics(metrics, intermediate_outputs, config)\n\n if config.use_dpo:\n new_state = _merge_dpo_state(new_state, reference_params)\n\n return new_state, metrics\n\n\ndef eval_step(model, config, state, data, dropout_rng):\n """"""eval_step no backprop and new state compared with train_step.""""""\n\n reference_params, extra_dpo_args, _loss_fn = [], [], loss_fn\n if config.use_dpo:\n state, reference_params = _split_dpo_state(state)\n extra_dpo_args = [reference_params]\n _loss_fn = dpo_loss_fn\n\n eval_loss_fn = functools.partial(_loss_fn, model, config, data, dropout_rng, is_train=False)\n loss, aux = eval_loss_fn(state.params, *extra_dpo_args)\n\n mtp_acceptance_rate = 0.0\n if config.mtp_eval_target_module > 0:\n mtp_acceptance_rate = calculate_mtp_acceptance_rate(aux[""intermediate_outputs""], config)\n\n total_loss = aux[""total_loss""]\n total_weights = aux[""total_weights""]\n moe_lb_loss = aux[""moe_lb_loss""]\n mtp_loss = aux[""mtp_loss""]\n metrics = {\n ""scalar"": {\n ""evaluation/loss"": loss,\n ""evaluation/total_loss"": total_loss,\n ""evaluation/total_weights"": total_weights,\n ""evaluation/moe_lb_loss"": moe_lb_loss,\n ""evaluation/mtp_loss"": mtp_loss,\n ""evaluation/mtp_acceptance_rate_percent"": mtp_acceptance_rate,\n },\n }\n if config.use_dpo:\n metrics[""scalar""][""evaluation/dpo_reward_accuracy""] = aux[""reward_accuracy""]\n\n return metrics\n\n\ndef setup_train_loop(config, recorder, devices=None):\n """"""Set up prerequisites for the training loop -\n checkpoint_manager, PRNG keys, Mesh, Model and optimizer.\n Set up data iterator and tokenizer, initialize the model.\n\n Args:\n config\n recorder\n\n Returns:\n init_rng:\n checkpoint_manager: Orbax checkpointer\n state_mesh_annotations: the mesh annotations for the train state\n model:\n mesh:\n learning_rate_schedule:\n data_iterator:\n state: the initialized train state\n """"""\n\n with maybe_record_goodput(recorder, GoodputEvent.TPU_INIT):\n model = mt.from_pretrained(config, devices)\n mesh = model.mesh\n init_rng, checkpoint_manager, learning_rate_schedule, tx = train_utils.create_training_tools(config, model, mesh)\n\n with maybe_record_goodput(recorder, GoodputEvent.TRAINING_PREPARATION):\n data_iterator, eval_data_iterator = create_data_iterator(config, mesh)\n context_parallel_size = config.context_parallel_size\n # Check if context parallelism is being used with sequence packing\n if context_parallel_size > 1 and config.packing and config.dataset_type != ""synthetic"":\n raise ValueError(\n ""Context parallelism cannot be used with sequence packing except for synthetic data where packing is not applied. ""\n ""Either disable sequence packing (set packing=False) or disable context parallelism. ""\n ""Context parallelism with packing support will be added soon.""\n )\n\n # Apply reordering wrapper to data iterators if context parallelism is enabled\n with mesh:\n if context_parallel_size > 1 and config.context_parallel_load_balance:\n data_iterator = map(max_utils.get_reorder_callable(context_parallel_size), data_iterator)\n if eval_data_iterator:\n eval_data_iterator = map(max_utils.get_reorder_callable(context_parallel_size), eval_data_iterator)\n\n state, _, state_mesh_shardings, data_iterator = maxtext_utils.setup_training_state(\n model, data_iterator, tx, config, init_rng, mesh, checkpoint_manager\n )\n\n # TODO(aireenmei, hengtaoguo): support sharding in vit for multimodal\n if not config.using_pipeline_parallelism and not config.use_multimodal:\n # The vocab tensor(s) of shape [vocab, embed] (and transpose) are not sharded by stage\n maxtext_utils.assert_params_sufficiently_sharded(state.params, mesh, config.sharding_tolerance)\n\n if config.use_dpo:\n abstract_state, _, _ = maxtext_utils.get_abstract_state(model, tx, config, init_rng, mesh, is_training=True)\n max_logging.log(f""Restoring reference parameters for DPO from '{os.path.join(str(config.checkpoint_dir), str(0))}'"")\n try:\n step0_restored, _ = checkpointing.load_state_if_possible(\n checkpoint_manager,\n data_iterator,\n load_parameters_from_path="""",\n load_full_state_from_path="""",\n checkpoint_storage_concurrent_gb=config.checkpoint_storage_concurrent_gb,\n abstract_unboxed_pre_state=abstract_state,\n enable_single_replica_ckpt_restoring=False,\n dataset_type=config.dataset_type,\n step=0,\n use_ocdbt=config.checkpoint_storage_use_ocdbt,\n use_zarr3=config.checkpoint_storage_use_zarr3,\n enable_orbax_v1=config.enable_orbax_v1,\n checkpoint_conversion_fn=config.checkpoint_conversion_fn,\n source_checkpoint_layout=config.source_checkpoint_layout,\n )\n except FileNotFoundError:\n step0_restored = None\n if step0_restored is not None:\n reference_params = step0_restored[""items""].params[""params""]\n state = _merge_dpo_state(state, reference_params)\n else:\n max_logging.log(\n f""Could not restore reference parameters for DPO from '{os.path.join(str(config.checkpoint_dir), str(0))}'""\n )\n\n return (\n init_rng,\n checkpoint_manager,\n state_mesh_shardings,\n model,\n mesh,\n learning_rate_schedule,\n data_iterator,\n eval_data_iterator,\n state,\n )\n\n\ndef train_loop(config, recorder, state=None):\n """"""Main Training loop.""""""\n (\n init_rng,\n checkpoint_manager,\n state_mesh_shardings,\n model,\n mesh,\n learning_rate_schedule,\n data_iterator,\n eval_data_iterator,\n state,\n ) = setup_train_loop(config, recorder)\n\n if config.use_dpo:\n if ""reference_params"" not in state.params:\n reference_params = jax.tree.map(jnp.copy, state.params[""params""])\n state = _merge_dpo_state(state, reference_params)\n state_mesh_shardings = _merge_dpo_state(state_mesh_shardings, state_mesh_shardings.params[""params""])\n\n p_train_step, p_eval_step = train_utils.jit_train_and_eval_step(\n config, model, mesh, state, state_mesh_shardings, train_step, eval_step, eval_data_iterator\n )\n\n with mesh, nn_partitioning.axis_rules(config.logical_axis_rules):\n shaped_batch = maxtext_utils.get_shaped_batch(config)\n compiled = p_train_step.lower(state, shaped_batch, init_rng).compile()\n compiled_stats = compiled.memory_analysis()\n max_utils.print_compiled_memory_stats(compiled_stats)\n\n start_step = get_first_step(state) # this is the start_step for training\n prof = profiler.Profiler(config, offset_step=start_step)\n data_loader = DataLoader(config, mesh, data_iterator, recorder)\n metric_logger = MetricLogger(config=config, learning_rate_schedule=learning_rate_schedule)\n\n # Write train config params, num model params, and XLA flags to tensorboard\n metric_logger.write_setup_info_to_tensorboard(state.params)\n\n try:\n last_step_completion = datetime.datetime.now()\n for step in np.arange(start_step, config.steps):\n prof.maybe_activate_profiler(step, state)\n\n with jax.profiler.StepTraceAnnotation(""train"", step_num=step):\n example_batch = data_loader.load_next_batch()\n # pylint: disable=not-callable\n nextrng = jax.jit(jax.random.fold_in)(init_rng, step)\n with maybe_record_goodput(recorder, GoodputEvent.STEP, step):\n with mesh, nn_partitioning.axis_rules(config.logical_axis_rules):\n state, metrics = p_train_step(state, example_batch, nextrng)\n\n step_time_delta = datetime.datetime.now() - last_step_completion\n last_step_completion = datetime.datetime.now()\n\n state_to_save = state if not config.use_dpo else _split_dpo_state(state)[0]\n checkpointing.maybe_save_checkpoint(checkpoint_manager, state_to_save, config, data_iterator, step)\n\n if config.dump_hlo and step == (config.dump_step if config.dump_step >= 0 else start_step):\n jax.block_until_ready(state) # Ensure compilation has finished.\n gcs_utils.upload_dump(\n config.dump_hlo_local_dir,\n config.dump_hlo_gcs_dir,\n module_name=config.dump_hlo_module_name,\n delete_local_after=config.dump_hlo_delete_local_after,\n all_host_upload=config.dump_hlo_upload_all,\n )\n\n if config.eval_interval > 0 and step > start_step and (step + 1) % config.eval_interval == 0:\n assert eval_data_iterator\n\n # Explicitly reset the eval counters before starting the eval loop\n metric_logger.reset_eval_metrics()\n\n eval_step_count = 0\n # pylint: disable=not-callable\n for eval_batch in eval_data_iterator:\n if config.eval_steps > 0 and eval_step_count >= config.eval_steps:\n break\n with mesh, nn_partitioning.axis_rules(config.logical_axis_rules):\n eval_metrics = p_eval_step(state, eval_batch, nextrng)\n metric_logger.record_eval_metrics(step, metrics=eval_metrics)\n max_logging.log(f""Completed eval step {eval_step_count}"")\n eval_step_count += 1\n metric_logger.record_eval_metrics(step, eval_step_count=eval_step_count)\n if metric_logger.cumulative_eval_metrics[""scalar""][""eval/avg_loss""] <= config.target_eval_loss:\n prof.deactivate()\n raise exceptions.StopTraining(f""Target loss {config.target_eval_loss=} is achieved."")\n\n prof.maybe_deactivate_profiler(step, state)\n\n if step == start_step:\n max_utils.print_mem_stats(""After params initialized"")\n\n metric_logger.buffer_and_write_train_metrics(metrics, step, step_time_delta)\n\n state_to_save = state if not config.use_dpo else _split_dpo_state(state)[0]\n checkpointing.maybe_save_checkpoint(checkpoint_manager, state_to_save, config, data_iterator)\n except exceptions.StopTraining as e:\n max_logging.log(f""Training stopped: {str(e)}"")\n finally:\n metric_logger.flush_metrics_and_cleanup()\n\n return state\n\n\ndef initialize(argv: Sequence[str]) -> tuple[pyconfig.HyperParameters, Any, Any]:\n """"""Initialization of hyperparameters and utilities""""""\n pathwaysutils.initialize()\n jax.config.update(""jax_default_prng_impl"", ""unsafe_rbg"")\n # TF allocates extraneous GPU memory when using TFDS data\n # this leads to CUDA OOMs. WAR for now is to hide GPUs from TF\n tf.config.set_visible_devices([], ""GPU"")\n os.environ[""TF_CPP_MIN_LOG_LEVEL""] = ""0""\n if ""xla_tpu_spmd_rng_bit_generator_unsafe"" not in os.environ.get(""LIBTPU_INIT_ARGS"", """"):\n os.environ[""LIBTPU_INIT_ARGS""] = (\n os.environ.get(""LIBTPU_INIT_ARGS"", """") + "" --xla_tpu_spmd_rng_bit_generator_unsafe=true""\n )\n # TODO: mazumdera@ : ensure missing mandatory fields in base.yml are filled in in argv,\n # or fill in here\n config = pyconfig.initialize(argv)\n jax.config.update(""jax_use_shardy_partitioner"", config.shardy)\n max_utils.print_system_information()\n validate_train_config(config)\n os.environ[""TFDS_DATA_DIR""] = config.dataset_path or """"\n vertex_tensorboard_manager = VertexTensorboardManager()\n if config.use_vertex_tensorboard or os.environ.get(""UPLOAD_DATA_TO_TENSORBOARD""):\n vertex_tensorboard_manager.configure_vertex_tensorboard(config)\n\n # Goodput configurations\n maybe_monitor_goodput(config)\n recorder = create_goodput_recorder(config)\n\n # Stack traces configurations\n debug_config = debug_configuration.DebugConfig(\n stack_trace_config=stack_trace_configuration.StackTraceConfig(\n collect_stack_trace=config.collect_stack_trace,\n stack_trace_to_cloud=config.stack_trace_to_cloud,\n stack_trace_interval_seconds=config.stack_trace_interval_seconds,\n )\n )\n diagnostic_config = diagnostic_configuration.DiagnosticConfig(debug_config)\n return config, recorder, diagnostic_config\n\n\ndef run(config, recorder, diagnostic_config):\n """"""Run the job given hyperparameters and utilities""""""\n with diagnostic.diagnose(diagnostic_config):\n with maybe_record_goodput(recorder, GoodputEvent.JOB):\n train_loop(config, recorder)\n\n\ndef main(argv: Sequence[str]) -> None:\n config, recorder, diagnostic_config = initialize(argv)\n run(config, recorder, diagnostic_config)\n\n\nif __name__ == ""__main__"":\n app.run(main)\n",python,tab
|
| 3 |
+
2,153,"anysphere.remote-ssh.Remote - SSH",0,0,"2025-08-30 08:23:46.468 [info] Resolving ssh remote authority 'login.haicore.berlin' (Unparsed 'ssh-remote+7b22686f73744e616d65223a226c6f67696e2e686169636f72652e6265726c696e227d') (attempt #1)\n2025-08-30 08:23:46.468 [info] SSH askpass server listening on /var/folders/nn/241fnlwx03d7k7qt2jg98txr0000gn/T/cursor-ssh-WqqEKj/socket.sock\n2025-08-30 08:23:46.468 [info] Using configured platform linux for remote host login.haicore.berlin\n2025-08-30 08:23:46.468 [info] Using askpass script: /Users/franzsrambical/.cursor/extensions/anysphere.remote-ssh-1.0.27/dist/scripts/launchSSHAskpass.sh with javascript file /Users/franzsrambical/.cursor/extensions/anysphere.remote-ssh-1.0.27/dist/scripts/sshAskClient.js. Askpass handle: /var/folders/nn/241fnlwx03d7k7qt2jg98txr0000gn/T/cursor-ssh-WqqEKj/socket.sock\n2025-08-30 08:23:46.468 [info] Launching SSH server via shell with command: cat ""/var/folders/nn/241fnlwx03d7k7qt2jg98txr0000gn/T/cursor_remote_install_1e914655-c41c-4abf-9dca-a83f158611b6.sh"" | ssh -T -D 50051 login.haicore.berlin bash --login -c bash\n2025-08-30 08:23:46.468 [info] Establishing SSH connection: cat ""/var/folders/nn/241fnlwx03d7k7qt2jg98txr0000gn/T/cursor_remote_install_1e914655-c41c-4abf-9dca-a83f158611b6.sh"" | ssh -T -D 50051 login.haicore.berlin bash --login -c bash\n2025-08-30 08:23:46.468 [info] Started installation script. Waiting for it to finish...\n2025-08-30 08:23:46.468 [info] Waiting for server to install...\n2025-08-30 08:23:48.602 [info] (ssh_tunnel) stdout: Configuring Cursor Server on Remote\n\n2025-08-30 08:23:48.607 [info] (ssh_tunnel) stdout: Using TMP_DIR: /run/user/961800067\n\n2025-08-30 08:23:48.651 [info] (ssh_tunnel) stdout: Locking /run/user/961800067/cursor-remote-lock.c403edc4db82e26fa41a0903d75ac6d0\nServer script already installed in /home/franz.srambical/.cursor-server/bin/af58d92614edb1f72bdd756615d131bf8dfa5290/bin/cursor-server\nChecking node executable\n\n2025-08-30 08:23:51.461 [info] (ssh_tunnel) stdout: v20.18.2\n\n2025-08-30 08:23:51.489 [info] (ssh_tunnel) stdout: Checking for running multiplex server: /home/franz.srambical/.cursor-server/bin/multiplex-server/45e440a0fc5a5d12380c7a83a49ab82c55f715a5d60292da31f8d75730a9ee15.js\n\n2025-08-30 08:23:51.493 [info] (ssh_tunnel) stdout: Running multiplex server: \n\n2025-08-30 08:23:51.503 [info] (ssh_tunnel) stdout: Creating multiplex server token file /run/user/961800067/cursor-remote-multiplex.token.c403edc4db82e26fa41a0903d75ac6d0.45e440a0fc5a5d12380c7a83a49ab82c55f715a5d60292da31f8d75730a9ee15\nCreating directory for multiplex server: /home/franz.srambical/.cursor-server/bin/multiplex-server\nWriting multiplex server script to /home/franz.srambical/.cursor-server/bin/multiplex-server/45e440a0fc5a5d12380c7a83a49ab82c55f715a5d60292da31f8d75730a9ee15.js\n\n2025-08-30 08:23:51.524 [info] (ssh_tunnel) stdout: Starting multiplex server: /home/franz.srambical/.cursor-server/bin/af58d92614edb1f72bdd756615d131bf8dfa5290/node /home/franz.srambical/.cursor-server/bin/multiplex-server/45e440a0fc5a5d12380c7a83a49ab82c55f715a5d60292da31f8d75730a9ee15.js 73d21401-808b-4db8-a118-a58136d9842f\n\n2025-08-30 08:23:51.559 [info] (ssh_tunnel) stdout: Multiplex server started with PID 1162616 and wrote pid to file /run/user/961800067/cursor-remote-multiplex.pid.c403edc4db82e26fa41a0903d75ac6d0.45e440a0fc5a5d12380c7a83a49ab82c55f715a5d60292da31f8d75730a9ee15\n\n2025-08-30 08:23:51.561 [info] (ssh_tunnel) stdout: Reading multiplex server token file /run/user/961800067/cursor-remote-multiplex.token.c403edc4db82e26fa41a0903d75ac6d0.45e440a0fc5a5d12380c7a83a49ab82c55f715a5d60292da31f8d75730a9ee15\nMultiplex server token file found\n\n2025-08-30 08:23:51.576 [info] (ssh_tunnel) stdout: Reading multiplex server log file /run/user/961800067/cursor-remote-multiplex.log.c403edc4db82e26fa41a0903d75ac6d0.45e440a0fc5a5d12380c7a83a49ab82c55f715a5d60292da31f8d75730a9ee15\n\n2025-08-30 08:23:52.015 [info] (ssh_tunnel) stdout: Checking for code servers\n\n2025-08-30 08:23:52.019 [info] (ssh_tunnel) stdout: Code server script is not running\nCreating code server token file /run/user/961800067/cursor-remote-code.token.c403edc4db82e26fa41a0903d75ac6d0\n\n2025-08-30 08:23:52.028 [info] (ssh_tunnel) stdout: Starting code server script /home/franz.srambical/.cursor-server/bin/af58d92614edb1f72bdd756615d131bf8dfa5290/bin/cursor-server --start-server --host=127.0.0.1 --port 0 --connection-token-file /run/user/961800067/cursor-remote-code.token.c403edc4db82e26fa41a0903d75ac6d0 --telemetry-level off --enable-remote-auto-shutdown --accept-server-license-terms &> /run/user/961800067/cursor-remote-code.log.c403edc4db82e26fa41a0903d75ac6d0 &\n\n2025-08-30 08:23:52.042 [info] (ssh_tunnel) stdout: Code server started with PID 1162642 and wrote pid to file /run/user/961800067/cursor-remote-code.pid.c403edc4db82e26fa41a0903d75ac6d0\nCode server log file is /run/user/961800067/cursor-remote-code.log.c403edc4db82e26fa41a0903d75ac6d0\n\n2025-08-30 08:23:53.036 [info] (ssh_tunnel) stdout: 28b315d79a492e7e37decfab: start\nexitCode==0==\nnodeExecutable==/home/franz.srambical/.cursor-server/bin/af58d92614edb1f72bdd756615d131bf8dfa5290/node==\nerrorMessage====\nisFatalError==false==\nmultiplexListeningOn==34349==\nmultiplexConnectionToken==73d21401-808b-4db8-a118-a58136d9842f==\ncodeListeningOn==37985==\ncodeConnectionToken==9928612f-1425-409f-959a-bb665a9ba1cb==\ndetectedPlatform==linux==\narch==x64==\nSSH_AUTH_SOCK====\n28b315d79a492e7e37decfab: end\n\n2025-08-30 08:23:53.037 [info] Server install command exit code: 0\n2025-08-30 08:23:53.037 [info] Deleting local script /var/folders/nn/241fnlwx03d7k7qt2jg98txr0000gn/T/cursor_remote_install_1e914655-c41c-4abf-9dca-a83f158611b6.sh\n2025-08-30 08:23:53.038 [info] [forwarding][code] creating new forwarding server\n2025-08-30 08:23:53.038 [info] [forwarding][code] server listening on 127.0.0.1:50230\n2025-08-30 08:23:53.038 [info] [forwarding][code] Set up server\n2025-08-30 08:23:53.038 [info] [remote-ssh] codeListeningOn (remote=127.0.0.1:37985; local=127.0.0.1:50230) codeConnectionToken: 9928612f-1425-409f-959a-bb665a9ba1cb\n2025-08-30 08:23:53.038 [info] [forwarding][multiplex] creating new forwarding server\n2025-08-30 08:23:53.038 [info] [forwarding][multiplex] server listening on 127.0.0.1:50231\n2025-08-30 08:23:53.038 [info] [forwarding][multiplex] Set up server\n2025-08-30 08:23:53.039 [info] [remote-ssh] multiplexListeningOn (remote=[object Object]; local=[object Object]) multiplexConnectionToken: 73d21401-808b-4db8-a118-a58136d9842f\n2025-08-30 08:23:53.039 [info] [remote-ssh] Pinging remote server via 127.0.0.1:50231...\n2025-08-30 08:23:53.040 [info] [remote-ssh] Resolved exec server. Socks port: 50051\n2025-08-30 08:23:53.040 [info] Setting up 0 default forwarded ports\n2025-08-30 08:23:53.040 [info] [remote-ssh] Resolved authority: {""host"":""127.0.0.1"",""port"":50230,""connectionToken"":""9928612f-1425-409f-959a-bb665a9ba1cb"",""extensionHostEnv"":{}}. Socks port: 50051\n2025-08-30 08:23:53.041 [info] (ssh_tunnel) stdout: Unlocking /run/user/961800067/cursor-remote-lock.c403edc4db82e26fa41a0903d75ac6d0\n\n2025-08-30 08:23:53.042 [info] [command][f91c8117-ff28-46dd-bbe0-e58fbd9bca53] Sending command request: {""command"":""echo"",""args"":[""1""],""env"":{},""token"":""73d21401-808b-4db8-a118-a58136d9842f"",""id"":""f91c8117-ff28-46dd-bbe0-e58fbd9bca53""}\n2025-08-30 08:23:53.044 [info] [forwarding][multiplex][127.0.0.1:50231 -> 127.0.0.1:34349][e028809c-00c8-455b-9314-10a55ce32c18] received connection request\n2025-08-30 08:23:53.044 [info] (ssh_tunnel) stdout: \n***********************************************************************\n* This terminal is used to establish and maintain the SSH connection. *\n\n2025-08-30 08:23:53.049 [info] (ssh_tunnel) stdout: * Closing this terminal will terminate the connection and disconnect *\n* Cursor from the remote server. *\n***********************************************************************\n\n2025-08-30 08:23:53.065 [info] [forwarding][code][127.0.0.1:50230 -> 127.0.0.1:37985][88f12b98-a37e-40cc-b40c-b0aad8be0d4c] received connection request\n2025-08-30 08:23:53.162 [info] [forwarding][multiplex][127.0.0.1:50231 -> 127.0.0.1:50051 -> 127.0.0.1:34349][e028809c-00c8-455b-9314-10a55ce32c18] socks forwarding established\n2025-08-30 08:23:53.180 [info] [forwarding][code][127.0.0.1:50230 -> 127.0.0.1:50051 -> 127.0.0.1:37985][88f12b98-a37e-40cc-b40c-b0aad8be0d4c] socks forwarding established\n2025-08-30 08:23:53.317 [info] [command][f91c8117-ff28-46dd-bbe0-e58fbd9bca53] Process exited with code 0\n2025-08-30 08:23:53.317 [info] [forwarding][multiplex][127.0.0.1:50231 -> 127.0.0.1:50051 -> 127.0.0.1:34349][e028809c-00c8-455b-9314-10a55ce32c18] socks connection closed\n2025-08-30 08:23:53.317 [info] [command][f91c8117-ff28-46dd-bbe0-e58fbd9bca53] Socket close event received\n2025-08-30 08:23:54.107 [info] [forwarding][code][127.0.0.1:50230 -> 127.0.0.1:37985][0fe9a149-4575-457c-bc01-bad144665ad4] received connection request\n2025-08-30 08:23:54.214 [info] [forwarding][code][127.0.0.1:50230 -> 127.0.0.1:50051 -> 127.0.0.1:37985][0fe9a149-4575-457c-bc01-bad144665ad4] socks forwarding established\n2025-08-30 08:23:54.622 [info] Saved platform linux for remote host login.haicore.berlin\n",log,tab
|
| 4 |
+
3,154,"MaxText/train.py",0,0,"",python,tab
|
| 5 |
+
4,301,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"9:24:03 AM [info] Activating crowd-code\n9:24:03 AM [info] Recording started\n9:24:03 AM [info] Initializing git provider using file system watchers...\n",Log,tab
|
| 6 |
+
5,432,"extension-output-pdoom-org.crowd-code-#1-crowd-code",150,0,"9:24:03 AM [info] Git repository found\n9:24:03 AM [info] Git provider initialized successfully\n9:24:04 AM [info] Initial git state: [object Object]\n",Log,content
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-29b02d56-00bb-4d54-ae16-3db6a9d130f81758358491962-2025_09_20-10.54.58.769/source.csv
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Sequence,Time,File,RangeOffset,RangeLength,Text,Language,Type
|
| 2 |
+
1,3,"input_pipeline/generate_atari_dataset.py",0,0,"# docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/rainbow/#rainbow_ataripy\nimport collections\nimport math\nimport os\nimport random\nimport time\nfrom collections import deque\nfrom dataclasses import dataclass\n\nimport gymnasium as gym\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport tyro\nfrom typing import Optional, Any\nfrom torch.utils.tensorboard.writer import SummaryWriter\n\nfrom cleanrl_utils.atari_wrappers import (\n ClipRewardEnv,\n EpisodicLifeEnv,\n FireResetEnv,\n MaxAndSkipEnv,\n NoopResetEnv,\n)\ntry:\n from utils import save_chunks # type: ignore\nexcept Exception: # pragma: no cover\n from input_pipeline.utils import save_chunks # type: ignore\nimport json\n\n\n@dataclass\nclass Args:\n exp_name: str = os.path.basename(__file__)[: -len("".py"")]\n """"""the name of this experiment""""""\n seed: int = 1\n """"""seed of the experiment""""""\n torch_deterministic: bool = True\n """"""if toggled, `torch.backends.cudnn.deterministic=False`""""""\n cuda: bool = True\n """"""if toggled, cuda will be enabled by default""""""\n track: bool = False\n """"""if toggled, this experiment will be tracked with Weights and Biases""""""\n wandb_project_name: str = ""cleanRL""\n """"""the wandb's project name""""""\n wandb_entity: Optional[str] = None\n """"""the entity (team) of wandb's project""""""\n capture_video: bool = False\n """"""whether to capture videos of the agent performances (check out `videos` folder)""""""\n save_model: bool = False\n """"""whether to save model into the `runs/{run_name}` folder""""""\n upload_model: bool = False\n """"""whether to upload the saved model to huggingface""""""\n hf_entity: str = """"\n """"""the user or org name of the model repository from the Hugging Face Hub""""""\n\n env_id: str = ""BreakoutNoFrameskip-v4""\n """"""the id of the environment""""""\n total_timesteps: int = 10000000\n """"""total timesteps of the experiments""""""\n learning_rate: float = 0.0000625\n """"""the learning rate of the optimizer""""""\n num_envs: int = 1\n """"""the number of parallel game environments""""""\n buffer_size: int = 1000000\n """"""the replay memory buffer size""""""\n gamma: float = 0.99\n """"""the discount factor gamma""""""\n tau: float = 1.0\n """"""the target network update rate""""""\n target_network_frequency: int = 8000\n """"""the timesteps it takes to update the target network""""""\n batch_size: int = 32\n """"""the batch size of sample from the reply memory""""""\n start_e: float = 1\n """"""the starting epsilon for exploration""""""\n end_e: float = 0.01\n """"""the ending epsilon for exploration""""""\n exploration_fraction: float = 0.10\n """"""the fraction of `total-timesteps` it takes from start-e to go end-e""""""\n learning_starts: int = 80000\n """"""timestep to start learning""""""\n train_frequency: int = 4\n """"""the frequency of training""""""\n n_step: int = 3\n """"""the number of steps to look ahead for n-step Q learning""""""\n prioritized_replay_alpha: float = 0.5\n """"""alpha parameter for prioritized replay buffer""""""\n prioritized_replay_beta: float = 0.4\n """"""beta parameter for prioritized replay buffer""""""\n prioritized_replay_eps: float = 1e-6\n """"""epsilon parameter for prioritized replay buffer""""""\n n_atoms: int = 51\n """"""the number of atoms""""""\n v_min: float = -10\n """"""the return lower bound""""""\n v_max: float = 10\n """"""the return upper bound""""""\n\n # Dataset capture\n capture_dataset: bool = True\n num_episodes_train: int = 10000\n num_episodes_val: int = 500\n num_episodes_test: int = 500\n output_dir: str = ""data/atari_episodes""\n min_episode_length: int = 1\n chunk_size: int = 160\n chunks_per_file: int = 100\n stop_on_complete: bool = True\n\n\ndef make_env(env_id, seed, idx, capture_video, run_name):\n def thunk():\n if capture_video and idx == 0:\n env = gym.make(env_id, render_mode=""rgb_array"")\n env = gym.wrappers.RecordVideo(env, f""videos/{run_name}"")\n else:\n env = gym.make(env_id)\n env = gym.wrappers.RecordEpisodeStatistics(env)\n\n env = NoopResetEnv(env, noop_max=30)\n env = MaxAndSkipEnv(env, skip=4)\n env = EpisodicLifeEnv(env)\n if ""FIRE"" in env.unwrapped.get_action_meanings():\n env = FireResetEnv(env)\n env = ClipRewardEnv(env)\n env = gym.wrappers.ResizeObservation(env, (84, 84))\n env = gym.wrappers.GrayScaleObservation(env)\n env = gym.wrappers.FrameStack(env, 4)\n\n env.action_space.seed(seed)\n return env\n\n return thunk\n\n\nclass NoisyLinear(nn.Module):\n def __init__(self, in_features, out_features, std_init=0.5):\n super().__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.std_init = std_init\n\n self.weight_mu = nn.Parameter(torch.FloatTensor(out_features, in_features))\n self.weight_sigma = nn.Parameter(torch.FloatTensor(out_features, in_features))\n self.register_buffer(""weight_epsilon"", torch.FloatTensor(out_features, in_features))\n self.bias_mu = nn.Parameter(torch.FloatTensor(out_features))\n self.bias_sigma = nn.Parameter(torch.FloatTensor(out_features))\n self.register_buffer(""bias_epsilon"", torch.FloatTensor(out_features))\n # factorized gaussian noise\n self.reset_parameters()\n self.reset_noise()\n\n def reset_parameters(self):\n mu_range = 1 / math.sqrt(self.in_features)\n self.weight_mu.data.uniform_(-mu_range, mu_range)\n self.weight_sigma.data.fill_(self.std_init / math.sqrt(self.in_features))\n self.bias_mu.data.uniform_(-mu_range, mu_range)\n self.bias_sigma.data.fill_(self.std_init / math.sqrt(self.out_features))\n\n def reset_noise(self):\n self.weight_epsilon.normal_()\n self.bias_epsilon.normal_()\n\n def forward(self, input):\n if self.training:\n weight = self.weight_mu + self.weight_sigma * self.weight_epsilon\n bias = self.bias_mu + self.bias_sigma * self.bias_epsilon\n else:\n weight = self.weight_mu\n bias = self.bias_mu\n return F.linear(input, weight, bias)\n\n\n# ALGO LOGIC: initialize agent here:\nclass NoisyDuelingDistributionalNetwork(nn.Module):\n def __init__(self, env, n_atoms, v_min, v_max):\n super().__init__()\n self.n_atoms = n_atoms\n self.v_min = v_min\n self.v_max = v_max\n self.delta_z = (v_max - v_min) / (n_atoms - 1)\n self.n_actions = env.single_action_space.n\n self.register_buffer(""support"", torch.linspace(v_min, v_max, n_atoms))\n\n self.network = nn.Sequential(\n nn.Conv2d(4, 32, 8, stride=4),\n nn.ReLU(),\n nn.Conv2d(32, 64, 4, stride=2),\n nn.ReLU(),\n nn.Conv2d(64, 64, 3, stride=1),\n nn.ReLU(),\n nn.Flatten(),\n )\n conv_output_size = 3136\n\n self.value_head = nn.Sequential(NoisyLinear(conv_output_size, 512), nn.ReLU(), NoisyLinear(512, n_atoms))\n\n self.advantage_head = nn.Sequential(\n NoisyLinear(conv_output_size, 512), nn.ReLU(), NoisyLinear(512, n_atoms * self.n_actions)\n )\n\n def forward(self, x):\n h = self.network(x / 255.0)\n value = self.value_head(h).view(-1, 1, self.n_atoms)\n advantage = self.advantage_head(h).view(-1, self.n_actions, self.n_atoms)\n q_atoms = value + advantage - advantage.mean(dim=1, keepdim=True)\n q_dist = F.softmax(q_atoms, dim=2)\n return q_dist\n\n def reset_noise(self):\n for layer in self.value_head:\n if isinstance(layer, NoisyLinear):\n layer.reset_noise()\n for layer in self.advantage_head:\n if isinstance(layer, NoisyLinear):\n layer.reset_noise()\n\n\nPrioritizedBatch = collections.namedtuple(\n ""PrioritizedBatch"", [""observations"", ""actions"", ""rewards"", ""next_observations"", ""dones"", ""indices"", ""weights""]\n)\n\n\n# adapted from: https://github.com/openai/baselines/blob/master/baselines/common/segment_tree.py\nclass SumSegmentTree:\n def __init__(self, capacity):\n self.capacity = capacity\n self.tree_size = 2 * capacity - 1\n self.tree = np.zeros(self.tree_size, dtype=np.float32)\n\n def _propagate(self, idx):\n parent = (idx - 1) // 2\n while parent >= 0:\n self.tree[parent] = self.tree[parent * 2 + 1] + self.tree[parent * 2 + 2]\n parent = (parent - 1) // 2\n\n def update(self, idx, value):\n tree_idx = idx + self.capacity - 1\n self.tree[tree_idx] = value\n self._propagate(tree_idx)\n\n def total(self):\n return self.tree[0]\n\n def retrieve(self, value):\n idx = 0\n while idx * 2 + 1 < self.tree_size:\n left = idx * 2 + 1\n right = left + 1\n if value <= self.tree[left]:\n idx = left\n else:\n value -= self.tree[left]\n idx = right\n return idx - (self.capacity - 1)\n\n\n# adapted from: https://github.com/openai/baselines/blob/master/baselines/common/segment_tree.py\nclass MinSegmentTree:\n def __init__(self, capacity):\n self.capacity = capacity\n self.tree_size = 2 * capacity - 1\n self.tree = np.full(self.tree_size, float(""inf""), dtype=np.float32)\n\n def _propagate(self, idx):\n parent = (idx - 1) // 2\n while parent >= 0:\n self.tree[parent] = np.minimum(self.tree[parent * 2 + 1], self.tree[parent * 2 + 2])\n parent = (parent - 1) // 2\n\n def update(self, idx, value):\n tree_idx = idx + self.capacity - 1\n self.tree[tree_idx] = value\n self._propagate(tree_idx)\n\n def min(self):\n return self.tree[0]\n\n\nclass PrioritizedReplayBuffer:\n def __init__(self, capacity, obs_shape, device, n_step, gamma, alpha=0.6, beta=0.4, eps=1e-6):\n self.capacity = capacity\n self.device = device\n self.n_step = n_step\n self.gamma = gamma\n self.alpha = alpha\n self.beta = beta\n self.eps = eps\n\n self.buffer_obs = np.zeros((capacity,) + obs_shape, dtype=np.uint8)\n self.buffer_next_obs = np.zeros((capacity,) + obs_shape, dtype=np.uint8)\n self.buffer_actions = np.zeros(capacity, dtype=np.int64)\n self.buffer_rewards = np.zeros(capacity, dtype=np.float32)\n self.buffer_dones = np.zeros(capacity, dtype=np.bool_)\n\n self.pos = 0\n self.size = 0\n self.max_priority = 1.0\n\n self.sum_tree = SumSegmentTree(capacity)\n self.min_tree = MinSegmentTree(capacity)\n\n # For n-step returns\n self.n_step_buffer = deque(maxlen=n_step)\n\n def _get_n_step_info(self):\n reward = 0.0\n next_obs = self.n_step_buffer[-1][3]\n done = self.n_step_buffer[-1][4]\n\n for i in range(len(self.n_step_buffer)):\n reward += self.gamma**i * self.n_step_buffer[i][2]\n if self.n_step_buffer[i][4]:\n next_obs = self.n_step_buffer[i][3]\n done = True\n break\n return reward, next_obs, done\n\n def add(self, obs, action, reward, next_obs, done):\n self.n_step_buffer.append((obs, action, reward, next_obs, done))\n\n if len(self.n_step_buffer) < self.n_step:\n return\n\n reward, next_obs, done = self._get_n_step_info()\n obs = self.n_step_buffer[0][0]\n action = self.n_step_buffer[0][1]\n\n idx = self.pos\n self.buffer_obs[idx] = obs\n self.buffer_next_obs[idx] = next_obs\n self.buffer_actions[idx] = action\n self.buffer_rewards[idx] = reward\n self.buffer_dones[idx] = done\n\n priority = self.max_priority**self.alpha\n self.sum_tree.update(idx, priority)\n self.min_tree.update(idx, priority)\n\n self.pos = (self.pos + 1) % self.capacity\n self.size = min(self.size + 1, self.capacity)\n\n if done:\n self.n_step_buffer.clear()\n\n def sample(self, batch_size):\n indices = []\n p_total = self.sum_tree.total()\n segment = p_total / batch_size\n\n for i in range(batch_size):\n a = segment * i\n b = segment * (i + 1)\n upperbound = np.random.uniform(a, b)\n idx = self.sum_tree.retrieve(upperbound)\n indices.append(idx)\n\n samples = {\n ""observations"": torch.from_numpy(self.buffer_obs[indices]).to(self.device),\n ""actions"": torch.from_numpy(self.buffer_actions[indices]).to(self.device).unsqueeze(1),\n ""rewards"": torch.from_numpy(self.buffer_rewards[indices]).to(self.device).unsqueeze(1),\n ""next_observations"": torch.from_numpy(self.buffer_next_obs[indices]).to(self.device),\n ""dones"": torch.from_numpy(self.buffer_dones[indices]).to(self.device).unsqueeze(1),\n }\n\n probs = np.array([self.sum_tree.tree[idx + self.capacity - 1] for idx in indices])\n weights = (self.size * probs / p_total) ** -self.beta\n weights = weights / weights.max()\n samples[""weights""] = torch.from_numpy(weights).to(self.device).unsqueeze(1)\n samples[""indices""] = indices\n\n return PrioritizedBatch(**samples)\n\n def update_priorities(self, indices, priorities):\n priorities = np.abs(priorities) + self.eps\n self.max_priority = max(self.max_priority, priorities.max())\n\n for idx, priority in zip(indices, priorities):\n priority = priority**self.alpha\n self.sum_tree.update(idx, priority)\n self.min_tree.update(idx, priority)\n\n\nif __name__ == ""__main__"":\n args = tyro.cli(Args)\n assert args.num_envs == 1, ""vectorized envs are not supported at the moment""\n run_name = f""{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}""\n if args.track:\n import wandb\n\n wandb.init(\n project=args.wandb_project_name,\n entity=args.wandb_entity,\n sync_tensorboard=True,\n config=vars(args),\n name=run_name,\n monitor_gym=True,\n save_code=True,\n )\n writer = SummaryWriter(f""runs/{run_name}"")\n writer.add_text(\n ""hyperparameters"",\n ""|param|value|\n|-|-|\n%s"" % (""\n"".join([f""|{key}|{value}|"" for key, value in vars(args).items()])),\n )\n\n # TRY NOT TO MODIFY: seeding\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n torch.backends.cudnn.deterministic = args.torch_deterministic\n\n device = torch.device(""cuda"" if torch.cuda.is_available() and args.cuda else ""cpu"")\n\n # env setup\n envs = gym.vector.SyncVectorEnv(\n [make_env(args.env_id, args.seed + i, i, args.capture_video, run_name) for i in range(args.num_envs)]\n )\n assert isinstance(envs.single_action_space, gym.spaces.Discrete), ""only discrete action space is supported""\n\n q_network = NoisyDuelingDistributionalNetwork(envs, args.n_atoms, args.v_min, args.v_max).to(device)\n optimizer = optim.Adam(q_network.parameters(), lr=args.learning_rate, eps=1.5e-4)\n target_network = NoisyDuelingDistributionalNetwork(envs, args.n_atoms, args.v_min, args.v_max).to(device)\n target_network.load_state_dict(q_network.state_dict())\n\n rb = PrioritizedReplayBuffer(\n args.buffer_size,\n envs.single_observation_space.shape,\n device,\n args.n_step,\n args.gamma,\n args.prioritized_replay_alpha,\n args.prioritized_replay_beta,\n args.prioritized_replay_eps,\n )\n\n # dataset capture state\n split_targets = {\n ""train"": args.num_episodes_train,\n ""val"": args.num_episodes_val,\n ""test"": args.num_episodes_test,\n }\n # Determine splits to run (order: train -> val -> test)\n splits_in_order = [s for s in [""train"", ""val"", ""test""] if split_targets[s] > 0]\n\n episodes_captured_per_split: dict[str, int] = {s: 0 for s in [""train"", ""val"", ""test""]}\n file_idx_by_split: dict[str, int] = {s: 0 for s in [""train"", ""val"", ""test""]}\n episode_metadata_by_split: dict[str, list[dict]] = {s: [] for s in [""train"", ""val"", ""test""]}\n\n obs_chunks: list[np.ndarray] = []\n act_chunks: list[np.ndarray] = []\n\n current_split_idx = 0\n current_split = splits_in_order[0]\n split_dir = os.path.join(args.output_dir, current_split)\n if args.capture_dataset:\n os.makedirs(split_dir, exist_ok=True)\n\n start_time = time.time()\n\n # TRY NOT TO MODIFY: start the game\n obs, _ = envs.reset(seed=args.seed)\n observations_seq: list[np.ndarray] = []\n actions_seq: list[np.ndarray] = []\n for global_step in range(args.total_timesteps):\n # anneal PER beta to 1\n rb.beta = min(\n 1.0, args.prioritized_replay_beta + global_step * (1.0 - args.prioritized_replay_beta) / args.total_timesteps\n )\n\n # ALGO LOGIC: put action logic here\n with torch.no_grad():\n q_dist = q_network(torch.Tensor(obs).to(device))\n q_values = torch.sum(q_dist * q_network.support, dim=2)\n actions = torch.argmax(q_values, dim=1).cpu().numpy()\n\n # TRY NOT TO MODIFY: execute the game and log data.\n next_obs, rewards, terminations, truncations, infos = envs.step(actions)\n\n if args.capture_dataset:\n observations_seq.append(next_obs.astype(np.uint8))\n actions_seq.append(actions.astype(np.int64))\n\n if ""final_info"" in infos:\n for info in infos[""final_info""]:\n if info and ""episode"" in info:\n print(f""global_step={global_step}, episodic_return={info['episode']['r']}"")\n writer.add_scalar(""charts/episodic_return"", info[""episode""][""r""], global_step)\n writer.add_scalar(""charts/episodic_length"", info[""episode""][""l""], global_step)\n\n continue_capturing_multi = any(\n episodes_captured_per_split[s] < split_targets[s]\n for s in splits_in_order\n )\n if args.capture_dataset and continue_capturing_multi:\n current_len = len(observations_seq)\n if current_len >= args.min_episode_length:\n frames = np.concatenate(observations_seq, axis=0).astype(np.uint8)\n acts = np.concatenate(actions_seq, axis=0).astype(np.int64)\n\n episode_obs_chunks = []\n episode_act_chunks = []\n start_idx = 0\n while start_idx < current_len:\n end_idx = min(start_idx + args.chunk_size, current_len)\n if end_idx - start_idx < args.chunk_size:\n print(\n f""Warning: Inconsistent chunk_sizes. Episode has {current_len} frames, ""\n f""which is smaller than the requested chunk_size: {args.chunk_size}. ""\n ""This might lead to performance degradation during training.""\n )\n episode_obs_chunks.append(frames[start_idx:end_idx][None, ...])\n episode_act_chunks.append(acts[start_idx:end_idx][None, ...])\n start_idx = end_idx\n\n obs_chunks_data = [\n np.concatenate(seq, axis=0).astype(np.uint8) for seq in episode_obs_chunks\n ]\n act_chunks_data = [np.concatenate(act, axis=0) for act in episode_act_chunks]\n obs_chunks.extend(obs_chunks_data)\n act_chunks.extend(act_chunks_data)\n\n # Save to the active split\n ep_metadata, obs_chunks, next_file_idx, act_chunks = save_chunks(\n obs_chunks,\n file_idx_by_split[current_split],\n args.chunks_per_file,\n split_dir,\n act_chunks,\n )\n file_idx_by_split[current_split] = next_file_idx\n episode_metadata_by_split[current_split].extend(ep_metadata)\n\n episodes_captured_per_split[current_split] += 1\n\n if episodes_captured_per_split[current_split] >= split_targets[current_split]:\n if len(obs_chunks) > 0:\n print(\n f""Warning: Dropping {len(obs_chunks)} chunks before switching split '"",{current_split},""' for consistent number of chunks per file."",\n ""Consider changing the chunk_size and chunks_per_file parameters to prevent data-loss."",\n )\n obs_chunks = []\n act_chunks = []\n if current_split_idx + 1 < len(splits_in_order):\n current_split_idx += 1\n current_split = splits_in_order[current_split_idx]\n split_dir = os.path.join(args.output_dir, current_split)\n os.makedirs(split_dir, exist_ok=True)\n else:\n print(f""Episode too short ({current_len}), skipping capture..."")\n\n observations_seq = []\n actions_seq = []\n\n # TRY NOT TO MODIFY: save data to reply buffer; handle `final_observation`\n real_next_obs = next_obs.copy()\n for idx, trunc in enumerate(truncations):\n if trunc:\n real_next_obs[idx] = infos[""final_observation""][idx]\n rb.add(obs, actions, rewards, real_next_obs, terminations)\n\n # TRY NOT TO MODIFY: CRUCIAL step easy to overlook\n obs = next_obs\n\n # ALGO LOGIC: training.\n if global_step > args.learning_starts:\n if global_step % args.train_frequency == 0:\n # reset the noise for both networks\n q_network.reset_noise()\n target_network.reset_noise()\n data = rb.sample(args.batch_size)\n\n with torch.no_grad():\n next_dist = target_network(data.next_observations) # [B, num_actions, n_atoms]\n support = target_network.support # [n_atoms]\n next_q_values = torch.sum(next_dist * support, dim=2) # [B, num_actions]\n\n # double q-learning\n next_dist_online = q_network(data.next_observations) # [B, num_actions, n_atoms]\n next_q_online = torch.sum(next_dist_online * support, dim=2) # [B, num_actions]\n best_actions = torch.argmax(next_q_online, dim=1) # [B]\n next_pmfs = next_dist[torch.arange(args.batch_size), best_actions] # [B, n_atoms]\n\n # compute the n-step Bellman update.\n gamma_n = args.gamma**args.n_step\n next_atoms = data.rewards + gamma_n * support * (1 - data.dones.float())\n tz = next_atoms.clamp(q_network.v_min, q_network.v_max)\n\n # projection\n delta_z = q_network.delta_z\n b = (tz - q_network.v_min) / delta_z # shape: [B, n_atoms]\n l = b.floor().clamp(0, args.n_atoms - 1)\n u = b.ceil().clamp(0, args.n_atoms - 1)\n\n # (l == u).float() handles the case where bj is exactly an integer\n # example bj = 1, then the upper ceiling should be uj= 2, and lj= 1\n d_m_l = (u.float() + (l == b).float() - b) * next_pmfs # [B, n_atoms]\n d_m_u = (b - l) * next_pmfs # [B, n_atoms]\n\n target_pmfs = torch.zeros_like(next_pmfs)\n for i in range(target_pmfs.size(0)):\n target_pmfs[i].index_add_(0, l[i].long(), d_m_l[i])\n target_pmfs[i].index_add_(0, u[i].long(), d_m_u[i])\n\n dist = q_network(data.observations) # [B, num_actions, n_atoms]\n pred_dist = dist.gather(1, data.actions.unsqueeze(-1).expand(-1, -1, args.n_atoms)).squeeze(1)\n log_pred = torch.log(pred_dist.clamp(min=1e-5, max=1 - 1e-5))\n\n loss_per_sample = -(target_pmfs * log_pred).sum(dim=1)\n loss = (loss_per_sample * data.weights.squeeze()).mean()\n\n # update priorities\n new_priorities = loss_per_sample.detach().cpu().numpy()\n rb.update_priorities(data.indices, new_priorities)\n\n if global_step % 100 == 0:\n writer.add_scalar(""losses/td_loss"", loss.item(), global_step)\n q_values = (pred_dist * q_network.support).sum(dim=1) # [B]\n writer.add_scalar(""losses/q_values"", q_values.mean().item(), global_step)\n sps = int(global_step / (time.time() - start_time))\n print(""SPS:"", sps)\n writer.add_scalar(""charts/SPS"", sps, global_step)\n writer.add_scalar(""charts/beta"", rb.beta, global_step)\n\n # optimize the model\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # update target network\n if global_step % args.target_network_frequency == 0:\n for target_param, param in zip(target_network.parameters(), q_network.parameters()):\n target_param.data.copy_(args.tau * param.data + (1.0 - args.tau) * target_param.data)\n\n # optional early stop on dataset completion\n if args.capture_dataset and args.stop_on_complete:\n all_done = all(\n episodes_captured_per_split[s] >= split_targets[s]\n for s in splits_in_order\n ) and len(splits_in_order) > 0\n if all_done:\n break\n\n envs.close()\n writer.close()\n\n # write metadata for dataset\n if args.capture_dataset:\n if len(obs_chunks) > 0:\n print(\n f""Warning: Dropping {len(obs_chunks)} chunks for consistent number of chunks per file."",\n ""Consider changing the chunk_size and chunks_per_file parameters to prevent data-loss."",\n )\n\n os.makedirs(args.output_dir, exist_ok=True)\n metadata_path = os.path.join(args.output_dir, ""metadata.json"")\n if os.path.exists(metadata_path):\n try:\n with open(metadata_path, ""r"") as f:\n metadata = json.load(f)\n except Exception:\n metadata = {}\n else:\n metadata = {}\n\n metadata.setdefault(""env"", args.env_id)\n metadata.setdefault(""num_actions"", int(envs.single_action_space.n))\n for split in [""train"", ""val"", ""test""]:\n metadata.setdefault(f""num_episodes_{split}"", 0)\n metadata.setdefault(f""avg_episode_len_{split}"", 0.0)\n metadata.setdefault(f""episode_metadata_{split}"", [])\n\n for split_key in splits_in_order:\n ep_meta_list = episode_metadata_by_split[split_key]\n if ep_meta_list:\n metadata[f""episode_metadata_{split_key}""].extend(ep_meta_list)\n metadata[f""num_episodes_{split_key}""] = len(metadata[f""episode_metadata_{split_key}""])\n metadata[f""avg_episode_len_{split_key}""] = float(\n np.mean([ep[""avg_seq_len""] for ep in metadata[f""episode_metadata_{split_key}""]])\n )\n\n with open(metadata_path, ""w"") as f:\n json.dump(metadata, f)\n""""""\nGenerates a dataset of random-action Atari episodes.\nEpisodes are saved individually as memory-mapped files for efficient loading.\nReplicates the behavior of generate_coinrun_dataset.py but for Atari.\n""""""\n\nfrom dataclasses import dataclass\n\nimport gymnasium as gym\nimport numpy as np\nimport tyro\nimport json\nimport os\nfrom cleanrl_utils.atari_wrappers import (\n ClipRewardEnv,\n EpisodicLifeEnv,\n FireResetEnv,\n MaxAndSkipEnv,\n NoopResetEnv,\n)\nfrom utils import save_chunks # type: ignore\n\n\n""""""\nOld dataset-only generator removed in favor of integrated Rainbow + capture mode.\n""""""\n",python,tab
|
| 3 |
+
2,187,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"10:54:58 AM [info] Activating crowd-code\n10:54:58 AM [info] Recording started\n10:54:58 AM [info] Initializing git provider using file system watchers...\n",Log,tab
|
| 4 |
+
3,280,"extension-output-pdoom-org.crowd-code-#1-crowd-code",153,0,"10:54:58 AM [info] Git repository found\n10:54:58 AM [info] Git provider initialized successfully\n10:54:58 AM [info] Initial git state: [object Object]\n",Log,content
|
| 5 |
+
4,2010,"input_pipeline/generate_atari_dataset.py",0,0,"",python,tab
|
| 6 |
+
5,4763,"TERMINAL",0,0,"",,terminal_command
|
| 7 |
+
6,8232,"input_pipeline/generate_atari_dataset.py",19419,0,"",python,selection_command
|
| 8 |
+
7,11646,"TERMINAL",0,0,"",,terminal_command
|
| 9 |
+
8,18513,"input_pipeline/generate_atari_dataset.py",0,0,"",python,tab
|
| 10 |
+
9,23548,"input_pipeline/generate_coinrun_dataset.py",0,0,"""""""\nGenerates a dataset of random-action CoinRun episodes.\nEpisodes are saved individually as memory-mapped files for efficient loading.\n""""""\n\nfrom dataclasses import dataclass\n\nfrom gym3 import types_np\nimport numpy as np\nfrom procgen import ProcgenGym3Env\nimport tyro\nimport json\nimport os\nfrom utils import save_chunks\n\n\n@dataclass\nclass Args:\n num_episodes_train: int = 10000\n num_episodes_val: int = 500\n num_episodes_test: int = 500\n output_dir: str = ""data/coinrun_episodes""\n min_episode_length: int = 1000\n max_episode_length: int = 1000\n chunk_size: int = 160\n chunks_per_file: int = 100\n seed: int = 0\n\n\nargs = tyro.cli(Args)\nassert (\n args.max_episode_length >= args.min_episode_length\n), ""Maximum episode length must be greater than or equal to minimum episode length.""\n\nif args.min_episode_length < args.chunk_size:\n print(\n ""Warning: Minimum episode length is smaller than chunk size. Note that episodes shorter than the chunk size will be discarded.""\n )\n\n\n# --- Generate episodes ---\ndef generate_episodes(num_episodes, split):\n episode_idx = 0\n episode_metadata = []\n obs_chunks = []\n act_chunks = []\n file_idx = 0\n output_dir_split = os.path.join(args.output_dir, split)\n while episode_idx < num_episodes:\n seed = np.random.randint(0, 10000)\n env = ProcgenGym3Env(num=1, env_name=""coinrun"", start_level=seed)\n\n observations_seq = []\n actions_seq = []\n episode_obs_chunks = []\n episode_act_chunks = []\n\n # --- Run episode ---\n step_t = 0\n for step_t in range(args.max_episode_length):\n action = types_np.sample(env.ac_space, bshape=(env.num,))\n env.act(action)\n _, obs, first = env.observe()\n observations_seq.append(obs[""rgb""])\n actions_seq.append(action)\n if len(observations_seq) == args.chunk_size:\n episode_obs_chunks.append(observations_seq)\n episode_act_chunks.append(actions_seq)\n observations_seq = []\n actions_seq = []\n if first:\n break\n\n # --- Save episode ---\n if step_t + 1 >= args.min_episode_length:\n if observations_seq:\n if len(observations_seq) < args.chunk_size:\n print(\n f""Warning: Inconsistent chunk_sizes. Episode has {len(observations_seq)} frames, ""\n f""which is smaller than the requested chunk_size: {args.chunk_size}. ""\n ""This might lead to performance degradation during training.""\n )\n episode_obs_chunks.append(observations_seq)\n episode_act_chunks.append(actions_seq)\n\n obs_chunks_data = [\n np.concatenate(seq, axis=0).astype(np.uint8)\n for seq in episode_obs_chunks\n ]\n act_chunks_data = [\n np.concatenate(act, axis=0) for act in episode_act_chunks\n ]\n obs_chunks.extend(obs_chunks_data)\n act_chunks.extend(act_chunks_data)\n\n ep_metadata, obs_chunks, file_idx, act_chunks = save_chunks(\n obs_chunks, file_idx, args.chunks_per_file, output_dir_split, act_chunks\n )\n episode_metadata.extend(ep_metadata)\n\n print(f""Episode {episode_idx} completed, length: {step_t + 1}."")\n episode_idx += 1\n else:\n print(f""Episode too short ({step_t + 1}), resampling..."")\n\n if len(obs_chunks) > 0:\n print(\n f""Warning: Dropping {len(obs_chunks)} chunks for consistent number of chunks per file."",\n ""Consider changing the chunk_size and chunks_per_file parameters to prevent data-loss."",\n )\n\n print(f""Done generating {split} split"")\n return episode_metadata\n\n\ndef get_action_space():\n env = ProcgenGym3Env(num=1, env_name=""coinrun"", start_level=0)\n return env.ac_space.eltype.n\n\n\ndef main():\n # Set random seed and create dataset directories\n np.random.seed(args.seed)\n # --- Generate episodes ---\n train_episode_metadata = generate_episodes(args.num_episodes_train, ""train"")\n val_episode_metadata = generate_episodes(args.num_episodes_val, ""val"")\n test_episode_metadata = generate_episodes(args.num_episodes_test, ""test"")\n\n # --- Save metadata ---\n metadata = {\n ""env"": ""coinrun"",\n ""num_actions"": get_action_space(),\n ""num_episodes_train"": args.num_episodes_train,\n ""num_episodes_val"": args.num_episodes_val,\n ""num_episodes_test"": args.num_episodes_test,\n ""avg_episode_len_train"": np.mean(\n [ep[""avg_seq_len""] for ep in train_episode_metadata]\n ),\n ""avg_episode_len_val"": np.mean(\n [ep[""avg_seq_len""] for ep in val_episode_metadata]\n ),\n ""avg_episode_len_test"": np.mean(\n [ep[""avg_seq_len""] for ep in test_episode_metadata]\n ),\n ""episode_metadata_train"": train_episode_metadata,\n ""episode_metadata_val"": val_episode_metadata,\n ""episode_metadata_test"": test_episode_metadata,\n }\n with open(os.path.join(args.output_dir, ""metadata.json""), ""w"") as f:\n json.dump(metadata, f)\n\n print(f""Done generating dataset."")\n\n\nif __name__ == ""__main__"":\n main()\n",python,tab
|
| 11 |
+
10,24637,"input_pipeline/generate_coinrun_dataset.py",2874,0,"",python,selection_command
|
| 12 |
+
11,24916,"input_pipeline/generate_coinrun_dataset.py",2920,0,"",python,selection_command
|
| 13 |
+
12,25140,"input_pipeline/generate_coinrun_dataset.py",2920,1,"]",python,selection_command
|
| 14 |
+
13,25389,"input_pipeline/generate_coinrun_dataset.py",2920,0,"",python,selection_command
|
| 15 |
+
14,25419,"input_pipeline/generate_coinrun_dataset.py",2920,1,"]",python,selection_command
|
| 16 |
+
15,25463,"input_pipeline/generate_coinrun_dataset.py",2920,0,"",python,selection_command
|
| 17 |
+
16,25488,"input_pipeline/generate_coinrun_dataset.py",2920,1,"]",python,selection_command
|
| 18 |
+
17,26078,"input_pipeline/generate_coinrun_dataset.py",2920,0,"",python,selection_command
|
| 19 |
+
18,26703,"input_pipeline/generate_coinrun_dataset.py",2908,13," ]",python,selection_command
|
| 20 |
+
19,27085,"input_pipeline/generate_coinrun_dataset.py",2862,59," for seq in episode_obs_chunks\n ]",python,selection_command
|
| 21 |
+
20,27161,"input_pipeline/generate_coinrun_dataset.py",2801,120," np.concatenate(seq, axis=0).astype(np.uint8)\n for seq in episode_obs_chunks\n ]",python,selection_command
|
| 22 |
+
21,27316,"input_pipeline/generate_coinrun_dataset.py",2769,152," obs_chunks_data = [\n np.concatenate(seq, axis=0).astype(np.uint8)\n for seq in episode_obs_chunks\n ]",python,selection_command
|
| 23 |
+
22,28038,"input_pipeline/generate_coinrun_dataset.py",2781,0,"",python,selection_command
|
| 24 |
+
23,28380,"input_pipeline/generate_coinrun_dataset.py",2769,31," obs_chunks_data = [",python,selection_command
|
| 25 |
+
24,28621,"input_pipeline/generate_coinrun_dataset.py",2769,92," obs_chunks_data = [\n np.concatenate(seq, axis=0).astype(np.uint8)",python,selection_command
|
| 26 |
+
25,28681,"input_pipeline/generate_coinrun_dataset.py",2769,138," obs_chunks_data = [\n np.concatenate(seq, axis=0).astype(np.uint8)\n for seq in episode_obs_chunks",python,selection_command
|
| 27 |
+
26,28824,"input_pipeline/generate_coinrun_dataset.py",2769,152," obs_chunks_data = [\n np.concatenate(seq, axis=0).astype(np.uint8)\n for seq in episode_obs_chunks\n ]",python,selection_command
|
| 28 |
+
27,28968,"input_pipeline/generate_coinrun_dataset.py",2769,184," obs_chunks_data = [\n np.concatenate(seq, axis=0).astype(np.uint8)\n for seq in episode_obs_chunks\n ]\n act_chunks_data = [",python,selection_command
|
| 29 |
+
28,29100,"input_pipeline/generate_coinrun_dataset.py",2769,258," obs_chunks_data = [\n np.concatenate(seq, axis=0).astype(np.uint8)\n for seq in episode_obs_chunks\n ]\n act_chunks_data = [\n np.concatenate(act, axis=0) for act in episode_act_chunks",python,selection_command
|
| 30 |
+
29,29240,"input_pipeline/generate_coinrun_dataset.py",2769,272," obs_chunks_data = [\n np.concatenate(seq, axis=0).astype(np.uint8)\n for seq in episode_obs_chunks\n ]\n act_chunks_data = [\n np.concatenate(act, axis=0) for act in episode_act_chunks\n ]",python,selection_command
|
| 31 |
+
30,45553,"input_pipeline/generate_coinrun_dataset.py",3040,0,"",python,selection_command
|
| 32 |
+
31,47017,"input_pipeline/generate_atari_dataset.py",0,0,"",python,tab
|
| 33 |
+
32,114269,"input_pipeline/generate_atari_dataset.py",19327,32," ",python,content
|
| 34 |
+
33,115169,"input_pipeline/generate_atari_dataset.py",19327,28," ",python,content
|
| 35 |
+
34,115848,"input_pipeline/generate_atari_dataset.py",19327,24," ",python,content
|
| 36 |
+
35,116066,"input_pipeline/generate_atari_dataset.py",19327,28," ",python,content
|
| 37 |
+
36,119988,"TERMINAL",0,0,"",,terminal_command
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-2a9bf505-97e2-485f-ae8a-8a5d3e22aceb1753782197393-2025_07_29-11.43.57.848/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-2f5b13c7-61f7-4340-b581-9edac6a53f1f1753015255059-2025_07_20-14.41.09.478/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-2fa035c7-d6bc-4ff1-a7cc-4b06be2f31801763194882325-2025_11_15-09.21.29.317/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-3ff5af95-247c-4adc-870c-57d666851fef1762448563284-2025_11_06-18.02.48.472/source.csv
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Sequence,Time,File,RangeOffset,RangeLength,Text,Language,Type
|
| 2 |
+
2,209,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"6:02:48 PM [info] Activating crowd-code\n6:02:48 PM [info] Recording started\n6:02:48 PM [info] Initializing git provider using file system watchers...\n",Log,tab
|
| 3 |
+
3,292,"extension-output-pdoom-org.crowd-code-#1-crowd-code",150,0,"6:02:48 PM [info] Git repository found\n6:02:48 PM [info] Git provider initialized successfully\n6:02:48 PM [info] Initial git state: [object Object]\n",Log,content
|
| 4 |
+
4,1746,"/home/franz.srambical/jafar/slurm/jobs/franz/berlin/atari/data_upload/upload_to_hf.sh",0,0,"#!/usr/bin/env bash\n\n#SBATCH --nodes=1\n#SBATCH --ntasks-per-node=1\n#SBATCH --time=24:00:00\n#SBATCH --cpus-per-task=8\n#SBATCH --gres=gpu:1\n#SBATCH --output=/fast/project/HFMI_SynergyUnit/jafar_ws/logs/franz/atari/data_upload/%x_%j.log\n#SBATCH --error=/fast/project/HFMI_SynergyUnit/jafar_ws/logs/franz/atari/data_upload/%x_%j.log\n#SBATCH --job-name=upload_to_hf\n\nsource .venv/bin/activate\n\npython slurm/utils/mihir/upload_hf_dataset.py /fast/project/HFMI_SynergyUnit/jafar_ws/data/atari/alien p-doom/atari-alien-dataset --repo-type dataset\npython slurm/utils/mihir/upload_hf_dataset.py /fast/project/HFMI_SynergyUnit/jafar_ws/data/atari/amidar p-doom/atari-amidar-dataset --repo-type dataset\npython slurm/utils/mihir/upload_hf_dataset.py /fast/project/HFMI_SynergyUnit/jafar_ws/data/atari/assault p-doom/atari-assault-dataset --repo-type dataset\npython slurm/utils/mihir/upload_hf_dataset.py /fast/project/HFMI_SynergyUnit/jafar_ws/data/atari/asterix p-doom/atari-asterix-dataset --repo-type dataset\npython slurm/utils/mihir/upload_hf_dataset.py /fast/project/HFMI_SynergyUnit/jafar_ws/data/atari/bank_heist p-doom/atari-bank_heist-dataset --repo-type dataset\npython slurm/utils/mihir/upload_hf_dataset.py /fast/project/HFMI_SynergyUnit/jafar_ws/data/atari/battle_zone p-doom/atari-battle_zone-dataset --repo-type dataset\npython slurm/utils/mihir/upload_hf_dataset.py /fast/project/HFMI_SynergyUnit/jafar_ws/data/atari/boxing p-doom/atari-boxing-dataset --repo-type dataset\npython slurm/utils/mihir/upload_hf_dataset.py /fast/project/HFMI_SynergyUnit/jafar_ws/data/atari/breakout p-doom/atari-breakout-dataset --repo-type dataset\npython slurm/utils/mihir/upload_hf_dataset.py /fast/project/HFMI_SynergyUnit/jafar_ws/data/atari/chopper_command p-doom/atari-chopper_command-dataset --repo-type dataset\npython slurm/utils/mihir/upload_hf_dataset.py /fast/project/HFMI_SynergyUnit/jafar_ws/data/atari/crazy_climber p-doom/atari-crazy_climber-dataset --repo-type dataset\npython slurm/utils/mihir/upload_hf_dataset.py /fast/project/HFMI_SynergyUnit/jafar_ws/data/atari/demon_attack p-doom/atari-demon_attack-dataset --repo-type dataset\npython slurm/utils/mihir/upload_hf_dataset.py /fast/project/HFMI_SynergyUnit/jafar_ws/data/atari/pong p-doom/atari-pong-dataset --repo-type dataset",shellscript,tab
|
| 5 |
+
5,1922,"slurm/dev/franz/berlin/crowd-pilot/launch_sglang_server.py",0,0,"from sglang.test.doc_patch import launch_server_cmd\nfrom sglang.utils import wait_for_server, print_highlight, terminate_process\n\n# This is equivalent to running the following command in your terminal\n# python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct --host 0.0.0.0\n\nserver_process, port = launch_server_cmd(\n """"""\npython3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct \\n --host 0.0.0.0 --log-level warning\n""""""\n)\n\nwait_for_server(f""http://localhost:{port}"")",python,tab
|
| 6 |
+
6,2088,"pyproject.toml",0,0,"[project]\nname = ""crowd-pilot""\ndescription = ""Teaching language models to code like humans.""\nversion = ""0.1.0""\nrequires-python = "">=3.12""\ndependencies = [\n ""datasets>=2.19.0"",\n ""pandas>=2.2.2"",\n ""pyarrow>=15.0.2"",\n ""tqdm>=4.66.4"",\n ""regex>=2024.5.15"",\n ""array-record>=0.8.1"",\n ""tensorflow>=2.20.0"",\n ""hf-transfer>=0.1.9"",\n]\n\n[project.urls]\nRepository = ""https://github.com/p-doom/crowd-pilot""\n",plaintext,tab
|
| 7 |
+
7,8684,"pyproject.toml",345,0,"",plaintext,selection_mouse
|
| 8 |
+
8,8686,"pyproject.toml",344,0,"",plaintext,selection_command
|
| 9 |
+
9,14532,"pyproject.toml",417,0,"",plaintext,selection_mouse
|
| 10 |
+
10,24147,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"",Log,tab
|
| 11 |
+
11,25926,"TERMINAL",0,0,"",,terminal_focus
|
| 12 |
+
12,25927,"pyproject.toml",0,0,"",plaintext,tab
|
| 13 |
+
13,26460,"TERMINAL",0,0,"source /home/franz.srambical/crowd-pilot/.venv/bin/activate",,terminal_command
|
| 14 |
+
14,26474,"TERMINAL",0,0,"]633;C]0;franz.srambical@hai-login2:~/crowd-pilot",,terminal_output
|
| 15 |
+
15,60122,"TERMINAL",0,0,"git submodule update",,terminal_command
|
| 16 |
+
16,60167,"TERMINAL",0,0,"]633;C",,terminal_output
|
| 17 |
+
17,60212,"TERMINAL",0,0,"]0;franz.srambical@hai-login2:~/crowd-pilot",,terminal_output
|
| 18 |
+
18,97627,"TERMINAL",0,0,"cd crowd-pilot-extension/",,terminal_command
|
| 19 |
+
19,99095,"TERMINAL",0,0,"git pull",,terminal_command
|
| 20 |
+
20,99139,"TERMINAL",0,0,"]633;C",,terminal_output
|
| 21 |
+
21,100576,"TERMINAL",0,0,"Already up to date.\r\n]0;franz.srambical@hai-login2:~/crowd-pilot/crowd-pilot-extension",,terminal_output
|
| 22 |
+
22,135797,"TERMINAL",0,0,"cd ..",,terminal_command
|
| 23 |
+
23,139570,"TERMINAL",0,0,"git submodule status",,terminal_command
|
| 24 |
+
24,139621,"TERMINAL",0,0,"]633;C",,terminal_output
|
| 25 |
+
25,139699,"TERMINAL",0,0,"-87a8e55c4d80472f6514b27d2233f80772e2d4b3 crowd-pilot-extension\r\n 3789aa17d7d3cf88c3a4db23c97127b1c2005bfc maxtext",,terminal_output
|
| 26 |
+
26,140174,"TERMINAL",0,0," (maxtext-v0.1.0-254-g3789aa17)\r\n]0;franz.srambical@hai-login2:~/crowd-pilot",,terminal_output
|
| 27 |
+
27,240996,"TERMINAL",0,0,"cd crowd-pilot",,terminal_command
|
| 28 |
+
28,242120,"TERMINAL",0,0,"ls -la",,terminal_command
|
| 29 |
+
29,242132,"TERMINAL",0,0,"]633;Ctotal 216\r\ndrwxr-xr-x 3 franz.srambical franz.srambical 247 Oct 25 15:32 [0m[01;34m.[0m\r\ndrwxr-xr-x 8 franz.srambical franz.srambical 299 Nov 6 18:03 [01;34m..[0m\r\n-rw-r--r-- 1 franz.srambical franz.srambical 9739 Oct 23 10:45 insert_missing_csv_newlines.py\r\ndrwxr-xr-x 2 franz.srambical franz.srambical 50 Oct 25 09:47 [01;34m__pycache__[0m\r\n-rw-r--r-- 1 franz.srambical franz.srambical 260 Oct 23 11:54 read_dataset.py\r\n-rw-r--r-- 1 franz.srambical franz.srambical 7525 Oct 25 15:32 serialization_utils.py\r\n-rw-r--r-- 1 franz.srambical franz.srambical 5777 Oct 25 15:32 serialize_dataset_array_record.py\r\n-rw-r--r-- 1 franz.srambical franz.srambical 4827 Oct 25 15:32 serialize_dataset_parquet.py\r\n]0;franz.srambical@hai-login2:~/crowd-pilot/crowd-pilot",,terminal_output
|
| 30 |
+
30,248897,"TERMINAL",0,0,"cd ../crowd-pilot-extension/",,terminal_command
|
| 31 |
+
31,250215,"TERMINAL",0,0,"ls -la",,terminal_command
|
| 32 |
+
32,250219,"TERMINAL",0,0,"]633;Ctotal 64\r\ndrwxr-xr-x 2 franz.srambical franz.srambical 0 Nov 6 18:03 [0m[01;34m.[0m\r\ndrwxr-xr-x 8 franz.srambical franz.srambical 299 Nov 6 18:03 [01;34m..[0m\r\n]0;franz.srambical@hai-login2:~/crowd-pilot/crowd-pilot-extension",,terminal_output
|
| 33 |
+
33,266625,"TERMINAL",0,0,"cd ..",,terminal_command
|
| 34 |
+
34,278756,"TERMINAL",0,0,"git submodule update --init crowd-pilot-extension",,terminal_command
|
| 35 |
+
35,278810,"TERMINAL",0,0,"]633;C",,terminal_output
|
| 36 |
+
36,278894,"TERMINAL",0,0,"Submodule 'crowd-pilot-extension' (git@github.com:p-doom/crowd-pilot-extension.git) registered for path 'crowd-pilot-extension'\r\nCloning into '/fast/home/franz.srambical/crowd-pilot/crowd-pilot-extension'...\r\n",,terminal_output
|
| 37 |
+
37,297397,"TERMINAL",0,0,"Submodule path 'crowd-pilot-extension': checked out '87a8e55c4d80472f6514b27d2233f80772e2d4b3'\r\n]0;franz.srambical@hai-login2:~/crowd-pilot",,terminal_output
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-41b294b4-b89c-4c1d-8a02-14afc9168dc41753085667665-2025_07_21-10.15.04.628/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-423369b5-91d4-45bc-a235-e640891c4f971759246484029-2025_09_30-17.34.52.514/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-42ef4ad5-d074-4f54-bd5e-892223ecd60a1762276234813-2025_11_04-18.10.41.464/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-43cc33c5-d808-49c3-aea6-b65ee92239d91763660422797-2025_11_20-18.40.29.930/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-46704c60-57ef-4934-8ea5-e02f81167b881756236789102-2025_08_26-21.33.18.58/source.csv
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Sequence,Time,File,RangeOffset,RangeLength,Text,Language,Type
|
| 2 |
+
1,3,"train_tokenizer.py",0,0,"import os\n\n# os.environ['XLA_FLAGS'] = (\n# '--xla_python_client_mem_fraction=.98 '\n# )\n# FIXME (f.srambical): test whether this increases throughput\n# os.environ['XLA_FLAGS'] = (\n# '--xla_gpu_enable_latency_hiding_scheduler=true '\n# '--xla_gpu_enable_async_collectives=true '\n# )\n\nfrom dataclasses import dataclass, field\nfrom typing import cast, Optional\n\nimport einops\nimport itertools\nfrom jax.sharding import Mesh, PartitionSpec, NamedSharding\nfrom jax.experimental.mesh_utils import create_device_mesh\nimport optax\nimport orbax.checkpoint as ocp\nimport numpy as np\nimport dm_pix as pix\nimport jax\nimport jax.numpy as jnp\nimport tyro\nimport wandb\nimport grain\nimport flax.nnx as nnx\n\nfrom models.tokenizer import TokenizerVQVAE\nfrom utils.dataloader import get_dataloader\nfrom utils.train_utils import (\n get_lr_schedule,\n count_parameters_by_component,\n print_mem_stats,\n print_compiled_memory_stats,\n print_compiled_cost_analysis,\n)\n\n\n@dataclass\nclass Args:\n # Experiment\n num_steps: int = 300_000\n seed: int = 0\n seq_len: int = 16\n image_channels: int = 3\n image_height: int = 90\n image_width: int = 160\n data_dir: str = """"\n save_ckpt: bool = False\n restore_ckpt: bool = False\n # Optimization\n vq_beta: float = 0.25\n batch_size: int = 48\n init_lr: float = 0.0\n max_lr: float = 3e-4\n decay_end: float = 0.0\n wsd_decay_steps: int = (\n 20000 # NOTE: wsd_decay_steps will only be used when using a wsd-schedule\n )\n lr_schedule: str = ""wsd"" # supported options: wsd, cos\n warmup_steps: int = 10000\n # Tokenizer\n model_dim: int = 512\n ffn_dim: int = 2048\n latent_dim: int = 32\n num_latents: int = 1024\n patch_size: int = 4\n num_blocks: int = 4\n num_heads: int = 8\n dropout: float = 0.0\n codebook_dropout: float = 0.01\n param_dtype = jnp.float32\n dtype = jnp.bfloat16\n # Logging\n log: bool = False\n entity: str = """"\n project: str = """"\n name: str = ""train_tokenizer""\n tags: list[str] = field(default_factory=lambda: [""tokenizer""])\n log_interval: int = 5\n log_image_interval: int = 250\n ckpt_dir: str = """"\n log_checkpoint_interval: int = 10000\n log_checkpoint_keep_period: int = 20000\n log_gradients: bool = False\n wandb_id: str = """"\n use_flash_attention: bool = True\n\n\ndef build_model(args: Args, rng: jax.Array) -> tuple[TokenizerVQVAE, jax.Array]:\n rng, _rng = jax.random.split(rng)\n rngs = nnx.Rngs(_rng)\n return (\n TokenizerVQVAE(\n in_dim=args.image_channels,\n model_dim=args.model_dim,\n ffn_dim=args.ffn_dim,\n latent_dim=args.latent_dim,\n num_latents=args.num_latents,\n patch_size=args.patch_size,\n num_blocks=args.num_blocks,\n num_heads=args.num_heads,\n dropout=args.dropout,\n codebook_dropout=args.codebook_dropout,\n param_dtype=args.param_dtype,\n dtype=args.dtype,\n use_flash_attention=args.use_flash_attention,\n rngs=rngs,\n ),\n rng,\n )\n\n\ndef build_optimizer(\n model: TokenizerVQVAE, args: Args\n) -> tuple[nnx.Optimizer, optax.Schedule]:\n lr_schedule = get_lr_schedule(\n args.lr_schedule,\n args.init_lr,\n args.max_lr,\n args.decay_end,\n args.num_steps,\n args.warmup_steps,\n args.wsd_decay_steps,\n )\n tx = optax.adamw(\n learning_rate=lr_schedule,\n b1=0.9,\n b2=0.9,\n weight_decay=1e-4,\n mu_dtype=args.param_dtype, # moments in full precision\n )\n optimizer = nnx.Optimizer(model, tx)\n return optimizer, lr_schedule\n\n\ndef build_mesh_and_sharding(\n num_devices: int,\n) -> tuple[Mesh, NamedSharding, NamedSharding]:\n device_mesh_arr = create_device_mesh((num_devices,))\n mesh = Mesh(devices=device_mesh_arr, axis_names=(""data"",))\n replicated_sharding = NamedSharding(mesh, PartitionSpec())\n videos_sharding = NamedSharding(mesh, PartitionSpec(""data"", None, None, None, None))\n return mesh, replicated_sharding, videos_sharding\n\n\ndef shard_optimizer_states(\n optimizer: nnx.Optimizer, replicated_sharding: NamedSharding\n) -> None:\n model_state = nnx.state(optimizer.model)\n model_sharded_state = jax.lax.with_sharding_constraint(\n model_state, replicated_sharding\n )\n nnx.update(optimizer.model, model_sharded_state)\n optimizer_state = nnx.state(optimizer, nnx.optimizer.OptState)\n optimizer_sharded_state = jax.lax.with_sharding_constraint(\n optimizer_state, replicated_sharding\n )\n nnx.update(optimizer, optimizer_sharded_state)\n\n\ndef build_dataloader(args: Args) -> grain.DataLoaderIterator:\n image_shape = (args.image_height, args.image_width, args.image_channels)\n array_record_files = [\n os.path.join(args.data_dir, x)\n for x in os.listdir(args.data_dir)\n if x.endswith("".array_record"")\n ]\n grain_dataloader = get_dataloader(\n array_record_files,\n args.seq_len,\n # NOTE: We deliberately pass the global batch size\n # The dataloader shards the dataset across all processes\n args.batch_size,\n *image_shape,\n num_workers=8,\n prefetch_buffer_size=1,\n seed=args.seed,\n )\n initial_state = grain_dataloader._create_initial_state()\n grain_iterator = grain.DataLoaderIterator(grain_dataloader, initial_state)\n return grain_iterator\n\n\ndef build_checkpoint_manager(args: Args) -> ocp.CheckpointManager:\n handler_registry = ocp.handlers.DefaultCheckpointHandlerRegistry()\n handler_registry.add(\n ""model_state"", ocp.args.PyTreeSave, ocp.handlers.PyTreeCheckpointHandler\n )\n handler_registry.add(\n ""model_state"", ocp.args.PyTreeRestore, ocp.handlers.PyTreeCheckpointHandler\n )\n handler_registry.add(\n ""dataloader_state"",\n grain.checkpoint.CheckpointSave,\n cast(ocp.handlers.CheckpointHandler, grain.checkpoint.CheckpointHandler),\n )\n handler_registry.add(\n ""dataloader_state"",\n grain.checkpoint.CheckpointRestore,\n cast(ocp.handlers.CheckpointHandler, grain.checkpoint.CheckpointHandler),\n )\n checkpoint_options = ocp.CheckpointManagerOptions(\n save_interval_steps=args.log_checkpoint_interval,\n max_to_keep=3,\n keep_period=args.log_checkpoint_keep_period,\n step_format_fixed_length=6,\n cleanup_tmp_directories=True,\n )\n checkpoint_manager = ocp.CheckpointManager(\n args.ckpt_dir,\n options=checkpoint_options,\n handler_registry=handler_registry,\n )\n return checkpoint_manager\n\n\ndef restore_checkpoint_if_needed(\n args: Args,\n checkpoint_manager: ocp.CheckpointManager,\n optimizer: nnx.Optimizer,\n grain_iterator: grain.DataLoaderIterator,\n restore_step: Optional[int] = None,\n) -> tuple[int, nnx.Optimizer, grain.DataLoaderIterator]:\n step = 0\n if restore_step is None:\n restore_step = checkpoint_manager.latest_step()\n if args.restore_ckpt:\n abstract_optimizer = nnx.eval_shape(lambda: optimizer)\n abstract_optimizer_state = nnx.state(abstract_optimizer)\n restored = checkpoint_manager.restore(\n restore_step,\n args=ocp.args.Composite(\n model_state=ocp.args.PyTreeRestore(abstract_optimizer_state), # type: ignore\n dataloader_state=grain.checkpoint.CheckpointRestore(grain_iterator), # type: ignore\n ),\n )\n restored_optimizer_state = restored[""model_state""]\n nnx.update(optimizer, restored_optimizer_state)\n grain_iterator = restored[""dataloader_state""]\n step = restore_step or 0\n print(f""Restored dataloader and model state from step {step}"")\n return step, optimizer, grain_iterator\n\n\ndef main(args: Args) -> None:\n jax.distributed.initialize()\n num_devices = jax.device_count()\n if num_devices == 0:\n raise ValueError(""No JAX devices found."")\n print(f""Running on {num_devices} devices."")\n\n if args.batch_size % num_devices != 0:\n raise ValueError(\n f""Global batch size {args.batch_size} must be divisible by ""\n f""number of devices {num_devices}.""\n )\n\n rng = jax.random.key(args.seed)\n\n # --- Initialize model ---\n tokenizer, rng = build_model(args, rng)\n\n _, params, _ = nnx.split(tokenizer, nnx.Param, ...)\n param_counts = count_parameters_by_component(params)\n\n if args.log and jax.process_index() == 0:\n wandb_init_kwargs = {\n ""entity"": args.entity,\n ""project"": args.project,\n ""name"": args.name,\n ""tags"": args.tags,\n ""group"": ""debug"",\n ""config"": args,\n }\n\n if args.wandb_id:\n wandb_init_kwargs.update(\n {\n ""id"": args.wandb_id,\n ""resume"": ""allow"",\n }\n )\n wandb.init(**wandb_init_kwargs)\n\n wandb.config.update({""model_param_count"": param_counts})\n\n print(""Parameter counts:"")\n print(param_counts)\n\n # --- Initialize optimizer ---\n optimizer, lr_schedule = build_optimizer(tokenizer, args)\n del tokenizer\n\n # FIXME: switch to create_hybrid_device_mesh for runs spanning multiple nodes\n mesh, replicated_sharding, videos_sharding = build_mesh_and_sharding(num_devices)\n\n shard_optimizer_states(optimizer, replicated_sharding)\n\n # --- Initialize checkpoint manager ---\n checkpoint_manager = build_checkpoint_manager(args)\n\n # --- Create DataLoaderIterator from dataloader ---\n grain_iterator = build_dataloader(args)\n\n # --- Restore checkpoint ---\n step, optimizer, grain_iterator = restore_checkpoint_if_needed(\n args, checkpoint_manager, optimizer, grain_iterator\n )\n\n # --- Define loss and train step (close over args) ---\n def tokenizer_loss_fn(\n model: TokenizerVQVAE, inputs: dict\n ) -> tuple[jax.Array, tuple[jax.Array, dict]]:\n gt = jnp.asarray(inputs[""videos""], dtype=jnp.float32) / 255.0\n inputs[""videos""] = gt.astype(args.dtype)\n model.train()\n outputs = model(inputs, training=True)\n outputs[""recon""] = outputs[""recon""].astype(jnp.float32)\n mse = jnp.square(gt - outputs[""recon""]).mean()\n q_loss = jnp.square(jax.lax.stop_gradient(outputs[""emb""]) - outputs[""z""]).mean()\n commitment_loss = jnp.square(\n outputs[""emb""] - jax.lax.stop_gradient(outputs[""z""])\n ).mean()\n loss = mse + q_loss + args.vq_beta * commitment_loss\n\n gt_clipped = gt.clip(0, 1).reshape(-1, *gt.shape[2:])\n recon = outputs[""recon""].clip(0, 1).reshape(-1, *outputs[""recon""].shape[2:])\n psnr = jnp.asarray(pix.psnr(gt_clipped, recon)).mean()\n ssim = jnp.asarray(pix.ssim(gt_clipped, recon)).mean()\n _, index_counts = jnp.unique_counts(\n jnp.ravel(outputs[""indices""]), size=args.num_latents, fill_value=0\n )\n codebook_usage = (index_counts != 0).mean()\n metrics = dict(\n loss=loss,\n mse=mse,\n q_loss=q_loss,\n commitment_loss=commitment_loss,\n psnr=psnr,\n ssim=ssim,\n codebook_usage=codebook_usage,\n )\n return loss, (outputs[""recon""], metrics)\n\n @nnx.jit(donate_argnums=0)\n def train_step(\n optimizer: nnx.Optimizer, inputs: dict\n ) -> tuple[jax.Array, jax.Array, dict]:\n def loss_fn(model: TokenizerVQVAE) -> tuple[jax.Array, tuple[jax.Array, dict]]:\n return tokenizer_loss_fn(model, inputs)\n\n (loss, (recon, metrics)), grads = nnx.value_and_grad(loss_fn, has_aux=True)(\n optimizer.model\n )\n optimizer.update(grads)\n if args.log_gradients:\n metrics[""encoder_gradients_std/""] = jax.tree.map(\n lambda x: x.std(), grads[""params""][""encoder""]\n )\n metrics[""vq_gradients_std/""] = jax.tree.map(\n lambda x: x.std(), grads[""params""][""vq""]\n )\n metrics[""decoder_gradients_std/""] = jax.tree.map(\n lambda x: x.std(), grads[""params""][""decoder""]\n )\n return loss, recon, metrics\n\n # --- TRAIN LOOP ---\n dataloader = (\n jax.make_array_from_process_local_data(videos_sharding, elem)\n for elem in grain_iterator\n )\n if jax.process_index() == 0:\n first_videos = next(dataloader)\n sample_inputs = dict(videos=first_videos)\n compiled = train_step.lower(optimizer, sample_inputs).compile()\n print_compiled_memory_stats(compiled.memory_analysis())\n print_compiled_cost_analysis(compiled.cost_analysis())\n # Do not skip the first batch during training\n dataloader = itertools.chain([first_videos], dataloader)\n print(f""Starting training from step {step}..."")\n first_step = step\n while step < args.num_steps:\n for videos in dataloader:\n # --- Train step ---\n inputs = dict(videos=videos)\n loss, recon, metrics = train_step(optimizer, inputs)\n if step == first_step:\n print_mem_stats(""After params initialized"")\n metrics[""lr""] = lr_schedule(step)\n print(f""Step {step}, loss: {loss}"")\n step += 1\n\n # --- Logging ---\n if args.log:\n if step % args.log_interval == 0 and jax.process_index() == 0:\n wandb.log(\n {\n ""loss"": loss,\n ""step"": step,\n **metrics,\n }\n )\n if step % args.log_image_interval == 0:\n gt_seq = inputs[""videos""][0].astype(jnp.float32) / 255.0\n recon_seq = recon[0].clip(0, 1)\n comparison_seq = jnp.concatenate((gt_seq, recon_seq), axis=1)\n comparison_seq = einops.rearrange(\n comparison_seq * 255, ""t h w c -> h (t w) c""\n )\n # NOTE: Process-dependent control flow deliberately happens\n # after indexing operation since it must not contain code\n # sections that lead to cross-accelerator communication.\n if jax.process_index() == 0:\n log_images = dict(\n image=wandb.Image(np.asarray(gt_seq[0])),\n recon=wandb.Image(np.asarray(recon_seq[0])),\n true_vs_recon=wandb.Image(\n np.asarray(comparison_seq.astype(np.uint8))\n ),\n )\n wandb.log(log_images)\n # --- Checkpointing ---\n if args.save_ckpt and step % args.log_checkpoint_interval == 0:\n optimizer_state = nnx.state(optimizer)\n checkpoint_manager.save(\n step,\n args=ocp.args.Composite(\n model_state=ocp.args.PyTreeSave(optimizer_state), # type: ignore\n dataloader_state=grain.checkpoint.CheckpointSave( # type: ignore\n grain_iterator # type: ignore\n ),\n ),\n )\n print(f""Saved checkpoint at step {step}"")\n if step >= args.num_steps:\n break\n\n checkpoint_manager.close()\n\n\nif __name__ == ""__main__"":\n args = tyro.cli(Args)\n main(args)\n",python,tab
|
| 3 |
+
2,162,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"9:33:18 PM [info] Activating crowd-code\n9:33:18 PM [info] Recording started\n9:33:18 PM [info] Initializing git provider using file system watchers...\n",Log,tab
|
| 4 |
+
3,338,"extension-output-pdoom-org.crowd-code-#1-crowd-code",150,0,"9:33:18 PM [info] Git repository found\n9:33:18 PM [info] Git provider initialized successfully\n9:33:18 PM [info] Initial git state: [object Object]\n",Log,content
|
| 5 |
+
4,14795,"TERMINAL",0,0,"",,terminal_focus
|
| 6 |
+
5,14796,"train_tokenizer.py",0,0,"",python,tab
|
| 7 |
+
6,15717,"TERMINAL",0,0,"source /home/franz.srambical/jafar/.venv/bin/activate",,terminal_command
|
| 8 |
+
7,17604,"TERMINAL",0,0,"salloc --gpus=1 --ntasks-per-node=1 --cpus-per-task=1 --mem=100G",,terminal_command
|
| 9 |
+
8,17661,"TERMINAL",0,0,"]633;Csalloc: Pending job allocation 24005\r\nsalloc: job 24005 queued and waiting for resources\r\n",,terminal_output
|
| 10 |
+
9,21162,"TERMINAL",0,0,"",,terminal_focus
|
| 11 |
+
10,21809,"TERMINAL",0,0,"source /home/franz.srambical/jafar/.venv/bin/activate",,terminal_command
|
| 12 |
+
11,26200,"TERMINAL",0,0,"squeue",,terminal_command
|
| 13 |
+
12,26230,"TERMINAL",0,0,"]633;C JOBID USER PARTITION NODES CPUS ST SUBMIT_TIME START_TIME TIME TIME_LIMIT NODELIST(REASON)\r\n 24005 franz.sram interacti 1 1 PD 2025-08-26T21:33:35 N/A 0:00 1-00:00:00 (Nodes required for job are DOWN, DRAINED or reserved for jobs in higher priority partitions)\r\n 23858 xiao.liu interacti 1 64 R 2025-08-26T10:11:29 2025-08-26T10:11:29 11:22:15 23:59:00 hai003\r\n 23857 xiao.liu interacti 1 64 R 2025-08-26T10:11:23 2025-08-26T10:11:23 11:22:21 23:59:00 hai002\r\n 23856 xiao.liu interacti 1 64 R 2025-08-26T10:10:41 2025-08-26T10:10:41 11:23:03 23:59:00 hai004\r\n 23941 yoland.sav standard 1 100 PD 2025-08-26T15:28:50 2025-08-27T00:43:24 0:00 1-00:00:00 (Priority)\r\n23921_4 yoland.sav standard 1 28 PD 2025-08-26T14:59:53 2025-08-26T23:00:30 0:00 4:00:00 (Resources)\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T21:28:10 5:34 4:00:00 hai008\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T21:12:34 21:10 4:00:00 hai003\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T20:56:40 37:04 4:00:00 hai007\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T20:43:24 50:20 4:00:00 hai006\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T20:35:57 57:47 4:00:00 hai005\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T20:31:10 1:02:34 4:00:00 hai005\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T20:19:59 1:13:45 4:00:00 hai004\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T20:15:05 1:18:39 4:00:00 hai002\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:57:59 1:35:45 4:00:00 hai007\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:49:58 1:43:46 4:00:00 hai006\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:48:55 1:44:49 4:00:00 hai004\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:47:01 1:46:43 4:00:00 hai008\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:30:25 2:03:19 4:00:00 hai008\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:00:30 2:33:14 4:00:00 hai005\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:00:30 2:33:14 4:00:00 hai007\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:00:30 2:33:14 4:00:00 hai003\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:00:30 2:33:14 4:00:00 hai006\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:00:25 2:33:19 4:00:00 hai002\r\n 23855 yoland.sav standard 1 128 R 2025-08-26T09:14:30 2025-08-26T09:14:31 12:19:13 1-00:00:00 hai001\r\n]0;franz.srambical@hai-login1:~/jafar",,terminal_output
|
| 14 |
+
13,30496,"TERMINAL",0,0,"salloc: job 24005 has been allocated resources\r\nsalloc: Granted job allocation 24005\r\n",,terminal_output
|
| 15 |
+
14,30584,"TERMINAL",0,0,"salloc: Nodes hai007 are ready for job\r\n",,terminal_output
|
| 16 |
+
15,30996,"TERMINAL",0,0,"Running inside SLURM, Job ID 24005.\r\n",,terminal_output
|
| 17 |
+
16,31052,"TERMINAL",0,0,"]0;franz.srambical@hai-login1:~/jafar[?2004h[franz.srambical@hai007.haicore.berlin:~/jafar] $ ",,terminal_output
|
| 18 |
+
17,43448,"TERMINAL",0,0,"exit",,terminal_command
|
| 19 |
+
18,43502,"TERMINAL",0,0,"]633;Cexit\r\n",,terminal_output
|
| 20 |
+
19,43718,"TERMINAL",0,0,"srun",,terminal_focus
|
| 21 |
+
20,43819,"TERMINAL",0,0,"\r[K[franz.srambical@hai007.haicore.berlin:~/jafar] $ ",,terminal_output
|
| 22 |
+
21,44588,"TERMINAL",0,0,"e",,terminal_output
|
| 23 |
+
22,45260,"TERMINAL",0,0,"[K",,terminal_output
|
| 24 |
+
23,49348,"TERMINAL",0,0,"\r(reverse-i-search)`': [K",,terminal_output
|
| 25 |
+
24,49653,"TERMINAL",0,0,"t': salloc --gpus=1 --ntasks-per-node=1 --cpus-per-[7mt[27mask=1 --mem=100G\r[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[Co': python3 -m MaxText.train MaxText/configs/base.yml run_name=h100_mfu_340m hardware=gpu dataset_type=synthetic steps=60 log_period=1 enable_checkpointing=False gcs_metrics=False metrics_file=/tmp/h100_mfu_metrics.jsonl base_output_directory=/tmp/maxtext attention=au[7mto[27mselected per_device_batch_size=4 base_emb_dim=1536 base_num_query_heads=12 base_num_kv_heads=12 base_mlp_dim=4096 base_num_decoder_layers=10 head_dim=128 logits_via_embedding=True[A[A[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[A\r[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[96Pk': bash experiments/dynamics_grain_[7mtok[27m_restore.sh \r\n\r[K\r\n\r[K\r\n\r[K[A[A[A[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C",,terminal_output
|
| 26 |
+
25,49725,"TERMINAL",0,0,"\r[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[4@e': bash experiments/[7mtoke[27mnizer_grain_checkpointing",,terminal_output
|
| 27 |
+
26,50374,"TERMINAL",0,0,"\r[24@[franz.srambical@hai007.haicore.berlin:~/jafar] $ bash experiments/toke\r\n[?2004l\r",,terminal_output
|
| 28 |
+
27,52914,"TERMINAL",0,0,"",,terminal_focus
|
| 29 |
+
28,53907,"TERMINAL",0,0,"source /home/franz.srambical/jafar/.venv/bin/activate",,terminal_command
|
| 30 |
+
29,53907,"TERMINAL",0,0,"]633;C]0;franz.srambical@hai-login1:~/jafar",,terminal_output
|
| 31 |
+
30,54954,"TERMINAL",0,0,"squeue",,terminal_command
|
| 32 |
+
31,54961,"TERMINAL",0,0,"]633;C JOBID USER PARTITION NODES CPUS ST SUBMIT_TIME START_TIME TIME TIME_LIMIT NODELIST(REASON)\r\n 24005 franz.sram interacti 1 2 R 2025-08-26T21:33:35 2025-08-26T21:33:48 0:24 1-00:00:00 hai007\r\n 23858 xiao.liu interacti 1 64 R 2025-08-26T10:11:29 2025-08-26T10:11:29 11:22:43 23:59:00 hai003\r\n 23857 xiao.liu interacti 1 64 R 2025-08-26T10:11:23 2025-08-26T10:11:23 11:22:49 23:59:00 hai002\r\n 23856 xiao.liu interacti 1 64 R 2025-08-26T10:10:41 2025-08-26T10:10:41 11:23:31 23:59:00 hai004\r\n 23941 yoland.sav standard 1 100 PD 2025-08-26T15:28:50 2025-08-27T00:43:24 0:00 1-00:00:00 (Priority)\r\n23921_4 yoland.sav standard 1 28 PD 2025-08-26T14:59:53 2025-08-26T23:00:30 0:00 4:00:00 (Resources)\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T21:28:10 6:02 4:00:00 hai008\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T21:12:34 21:38 4:00:00 hai003\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T20:56:40 37:32 4:00:00 hai007\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T20:43:24 50:48 4:00:00 hai006\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T20:35:57 58:15 4:00:00 hai005\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T20:31:10 1:03:02 4:00:00 hai005\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T20:19:59 1:14:13 4:00:00 hai004\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T20:15:05 1:19:07 4:00:00 hai002\r\n23921_4 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:57:59 1:36:13 4:00:00 hai007\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:49:58 1:44:14 4:00:00 hai006\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:48:55 1:45:17 4:00:00 hai004\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:47:01 1:47:11 4:00:00 hai008\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:30:25 2:03:47 4:00:00 hai008\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:00:30 2:33:42 4:00:00 hai005\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:00:30 2:33:42 4:00:00 hai007\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:00:30 2:33:42 4:00:00 hai003\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:00:30 2:33:42 4:00:00 hai006\r\n23921_3 yoland.sav standard 1 56 R 2025-08-26T14:59:53 2025-08-26T19:00:25 2:33:47 4:00:00 hai002\r\n 23855 yoland.sav standard 1 128 R 2025-08-26T09:14:30 2025-08-26T09:14:31 12:19:41 1-00:00:00 hai001\r\n]0;franz.srambical@hai-login1:~/jafar",,terminal_output
|
| 33 |
+
32,57102,"TERMINAL",0,0,"Running on 1 devices.\r\n",,terminal_output
|
| 34 |
+
33,61082,"TERMINAL",0,0,"Counting all components: ['decoder', 'encoder', 'vq']\r\nParameter counts:\r\n{'decoder': 16858736, 'encoder': 16858752, 'vq': 32768, 'total': 33750256}\r\n",,terminal_output
|
| 35 |
+
34,61104,"TERMINAL",0,0,"srun",,terminal_focus
|
| 36 |
+
35,74627,"TERMINAL",0,0,"g",,terminal_output
|
| 37 |
+
36,75160,"TERMINAL",0,0," ",,terminal_output
|
| 38 |
+
37,75929,"TERMINAL",0,0,"",,terminal_focus
|
| 39 |
+
38,76618,"TERMINAL",0,0,"source /home/franz.srambical/jafar/.venv/bin/activate",,terminal_command
|
| 40 |
+
39,77636,"TERMINAL",0,0,"git log",,terminal_command
|
| 41 |
+
40,77691,"TERMINAL",0,0,"]633;C",,terminal_output
|
| 42 |
+
41,77877,"TERMINAL",0,0,"[?1h=\r[33mcommit f43a45ebc910ef3f12edb9e98a43c71970f6cbaf[m[33m ([m[1;36mHEAD[m[33m -> [m[1;32msimplified-param-calculation[m[33m)[m[m\r\nAuthor: Franz Srambical <franz.srambical@gmail.com>[m\r\nDate: Mon Aug 25 10:45:11 2025 +0200[m\r\n[m\r\n chore: simplified parameter calculation[m\r\n[m\r\n[33mcommit cd214e3f31270330a658df15f70eeeb5b9608e2f[m[33m ([m[1;32mtokenizer-fwd-half-precision[m[33m)[m[m\r\nMerge: 3f4d73a b8d6036[m\r\nAuthor: emergenz <franz.srambical@gmail.com>[m\r\nDate: Sun Aug 24 14:38:05 2025 +0200[m\r\n[m\r\n Merge branch 'print-mem-stats-after-param-init' into tokenizer-fwd-half-precision[m\r\n:[K",,terminal_output
|
| 43 |
+
42,87026,"TERMINAL",0,0,"\r[K[?1l>]0;franz.srambical@hai-login1:~/jafar",,terminal_output
|
| 44 |
+
43,88728,"TERMINAL",0,0,"srun",,terminal_focus
|
| 45 |
+
44,101800,"TERMINAL",0,0,"2025-08-26 21:34:59.774653: E external/xla/xla/stream_executor/cuda/cuda_timer.cc:86] Delay kernel timed out: measured time has sub-optimal accuracy. There may be a missing warmup execution, please investigate in Nsight Systems.\r\n",,terminal_output
|
| 46 |
+
45,102115,"TERMINAL",0,0,"2025-08-26 21:35:00.055090: E external/xla/xla/stream_executor/cuda/cuda_timer.cc:86] Delay kernel timed out: measured time has sub-optimal accuracy. There may be a missing warmup execution, please investigate in Nsight Systems.\r\n",,terminal_output
|
| 47 |
+
46,112648,"TERMINAL",0,0,"Total memory size: 9.5 GB, Output size: 0.4 GB, Temp size: 9.0 GB, Argument size: 0.4 GB, Host temp size: 0.0 GB.\r\nFLOPs: 3.306e+11, Bytes: 2.483e+11 (231.2 GB), Intensity: 1.3 FLOPs/byte\r\nStarting training from step 0...\r\n",,terminal_output
|
| 48 |
+
47,112911,"TERMINAL",0,0,"\r\nMemstats: After params initialized:\r\n\tUsing (GB) 0.44 / 59.39 (0.740865%) on cuda:0\r\n",,terminal_output
|
| 49 |
+
48,113418,"TERMINAL",0,0,"Step 0, loss: 0.25431719422340393\r\n",,terminal_output
|
| 50 |
+
49,128244,"TERMINAL",0,0,"Step 1, loss: 0.26579394936561584\r\n",,terminal_output
|
| 51 |
+
50,128637,"TERMINAL",0,0,"Step 2, loss: 0.2766578793525696\r\n",,terminal_output
|
| 52 |
+
51,129136,"TERMINAL",0,0,"Step 3, loss: 0.25497928261756897\r\n",,terminal_output
|
| 53 |
+
52,129826,"TERMINAL",0,0,"Step 4, loss: 0.23926183581352234\r\nSaved checkpoint at step 5\r\n",,terminal_output
|
| 54 |
+
53,130318,"TERMINAL",0,0,"Step 5, loss: 0.22148826718330383\r\n",,terminal_output
|
| 55 |
+
54,131034,"TERMINAL",0,0,"Step 6, loss: 0.21240630745887756\r\n",,terminal_output
|
| 56 |
+
55,131400,"TERMINAL",0,0,"Step 7, loss: 0.20403112471103668\r\n",,terminal_output
|
| 57 |
+
56,131924,"TERMINAL",0,0,"Step 8, loss: 0.20164495706558228\r\n",,terminal_output
|
| 58 |
+
57,132504,"TERMINAL",0,0,"Step 9, loss: 0.19122974574565887\r\nSaved checkpoint at step 10\r\n",,terminal_output
|
| 59 |
+
58,132809,"TERMINAL",0,0,"Step 10, loss: 0.1849343180656433\r\n",,terminal_output
|
| 60 |
+
59,133159,"TERMINAL",0,0,"Step 11, loss: 0.18322879076004028\r\n",,terminal_output
|
| 61 |
+
60,133693,"TERMINAL",0,0,"Step 12, loss: 0.17462605237960815\r\n",,terminal_output
|
| 62 |
+
61,134115,"TERMINAL",0,0,"Step 13, loss: 0.1700616478919983\r\n",,terminal_output
|
| 63 |
+
62,134584,"TERMINAL",0,0,"Step 14, loss: 0.16311784088611603\r\nSaved checkpoint at step 15\r\n",,terminal_output
|
| 64 |
+
63,135305,"TERMINAL",0,0,"Step 15, loss: 0.16045361757278442\r\n",,terminal_output
|
| 65 |
+
64,135820,"TERMINAL",0,0,"Step 16, loss: 0.1573820263147354\r\n",,terminal_output
|
| 66 |
+
65,136385,"TERMINAL",0,0,"Step 17, loss: 0.15202277898788452\r\n",,terminal_output
|
| 67 |
+
66,137097,"TERMINAL",0,0,"Step 18, loss: 0.14372730255126953\r\n",,terminal_output
|
| 68 |
+
67,137641,"TERMINAL",0,0,"Step 19, loss: 0.13960416615009308\r\nSaved checkpoint at step 20\r\n",,terminal_output
|
| 69 |
+
68,138353,"TERMINAL",0,0,"Step 20, loss: 0.13812196254730225\r\n",,terminal_output
|
| 70 |
+
69,138904,"TERMINAL",0,0,"Step 21, loss: 0.1377347707748413\r\n",,terminal_output
|
| 71 |
+
70,139388,"TERMINAL",0,0,"Step 22, loss: 0.13599258661270142\r\n",,terminal_output
|
| 72 |
+
71,140155,"TERMINAL",0,0,"Step 23, loss: 0.13166093826293945\r\n",,terminal_output
|
| 73 |
+
72,140758,"TERMINAL",0,0,"Step 24, loss: 0.12757566571235657\r\nSaved checkpoint at step 25\r\n",,terminal_output
|
| 74 |
+
73,141471,"TERMINAL",0,0,"Step 25, loss: 0.12639828026294708\r\n",,terminal_output
|
| 75 |
+
74,142097,"TERMINAL",0,0,"Step 26, loss: 0.12637247145175934\r\n",,terminal_output
|
| 76 |
+
75,143048,"TERMINAL",0,0,"Step 27, loss: 0.12499938905239105\r\n",,terminal_output
|
| 77 |
+
76,143575,"TERMINAL",0,0,"Step 28, loss: 0.12089689075946808\r\n",,terminal_output
|
| 78 |
+
77,144011,"TERMINAL",0,0,"Step 29, loss: 0.11961660534143448\r\nSaved checkpoint at step 30\r\n",,terminal_output
|
| 79 |
+
78,144552,"TERMINAL",0,0,"Step 30, loss: 0.11981676518917084\r\n",,terminal_output
|
| 80 |
+
79,145183,"TERMINAL",0,0,"Step 31, loss: 0.1183973178267479\r\n",,terminal_output
|
| 81 |
+
80,145823,"TERMINAL",0,0,"Step 32, loss: 0.1157911866903305\r\n",,terminal_output
|
| 82 |
+
81,146348,"TERMINAL",0,0,"Step 33, loss: 0.11384514719247818\r\n",,terminal_output
|
| 83 |
+
82,147433,"TERMINAL",0,0,"Step 34, loss: 0.11437270045280457\r\nSaved checkpoint at step 35\r\n",,terminal_output
|
| 84 |
+
83,148124,"TERMINAL",0,0,"Step 35, loss: 0.11370142549276352\r\n",,terminal_output
|
| 85 |
+
84,148737,"TERMINAL",0,0,"Step 36, loss: 0.1110914945602417\r\n",,terminal_output
|
| 86 |
+
85,149210,"TERMINAL",0,0,"Step 37, loss: 0.10998664051294327\r\n",,terminal_output
|
| 87 |
+
86,149766,"TERMINAL",0,0,"Step 38, loss: 0.11073639988899231\r\n",,terminal_output
|
| 88 |
+
87,150367,"TERMINAL",0,0,"Step 39, loss: 0.10990631580352783\r\nSaved checkpoint at step 40\r\n",,terminal_output
|
| 89 |
+
88,151051,"TERMINAL",0,0,"Step 40, loss: 0.10790339857339859\r\n",,terminal_output
|
| 90 |
+
89,151909,"TERMINAL",0,0,"Step 41, loss: 0.10802937299013138\r\n",,terminal_output
|
| 91 |
+
90,152582,"TERMINAL",0,0,"Step 42, loss: 0.10871389508247375\r\n",,terminal_output
|
| 92 |
+
91,152958,"TERMINAL",0,0,"^Csrun: interrupt (one more within 1 sec to abort)\r\nsrun: StepId=24005.0 task 0: running\r\n",,terminal_output
|
| 93 |
+
92,153123,"TERMINAL",0,0,"^Csrun: sending Ctrl-C to StepId=24005.0\r\nsrun: forcing job termination\r\nsrun: Job step aborted: Waiting up to 32 seconds for job step to finish.\r\n[2025-08-26T21:35:51.088] error: *** STEP 24005.0 ON hai007 CANCELLED AT 2025-08-26T21:35:51 DUE to SIGNAL Killed ***\r\n",,terminal_output
|
| 94 |
+
93,153460,"TERMINAL",0,0,"^Csrun: sending Ctrl-C to StepId=24005.0\r\nsrun: job abort in progress\r\n",,terminal_output
|
| 95 |
+
94,153669,"TERMINAL",0,0,"]0;franz.srambical@hai-login1:~/jafar[?2004h[franz.srambical@hai007.haicore.berlin:~/jafar] $ ",,terminal_output
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-46a4cc9d-ac37-44ff-ae8d-547db76d96f31752072213286-2025_07_09-16.43.57.848/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-4719c5f9-1b15-4792-8afd-690761108bda1751617825355-2025_07_04-10.31.22.581/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-48d8454e-eb9c-4d78-a257-1c3ae6fff0eb1767631180086-2026_01_05-17.39.46.786/source.csv
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Sequence,Time,File,RangeOffset,RangeLength,Text,Language,Type
|
| 2 |
+
1,3,"package.json",0,0,"{\n ""name"": ""crowd-pilot"",\n ""displayName"": ""crowd-pilot-extension"",\n ""description"": ""Teaching language models to code like humans."",\n ""publisher"": ""p-doom"",\n ""version"": ""0.0.1"",\n ""repository"": {\n ""type"": ""git"",\n ""url"": ""https://github.com/p-doom/crowd-pilot-extension""\n },\n ""engines"": {\n ""vscode"": ""^1.99.3""\n },\n ""categories"": [\n ""Other""\n ],\n ""activationEvents"": [\n ""onStartupFinished""\n ],\n ""main"": ""./out/extension.js"",\n ""contributes"": {\n ""commands"": [\n {\n ""command"": ""crowd-pilot.toggleSuggestions"",\n ""title"": ""crowd-pilot: Toggle Tab Suggestions""\n },\n {\n ""command"": ""crowd-pilot.hideUi"",\n ""title"": ""crowd-pilot: Hide Preview""\n },\n {\n ""command"": ""crowd-pilot.sglangTest"",\n ""title"": ""crowd-pilot: Test SGLang""\n },\n {\n ""command"": ""crowd-pilot.modelRun"",\n ""title"": ""crowd-pilot: Model Plan & Run""\n },\n {\n ""command"": ""crowd-pilot.clearContext"",\n ""title"": ""crowd-pilot: Clear Context""\n },\n {\n ""command"": ""crowd-pilot.openPreferenceLog"",\n ""title"": ""crowd-pilot: Open Preference Log""\n },\n {\n ""command"": ""crowd-pilot.showPendingAction"",\n ""title"": ""crowd-pilot: Show Pending Suggestion""\n }\n ],\n ""configuration"": {\n ""title"": ""crowd-pilot"",\n ""properties"": {\n ""crowd-pilot.hostname"": {\n ""type"": ""string"",\n ""default"": ""hai002"",\n ""description"": ""Hostname of the SGLang server""\n },\n ""crowd-pilot.port"": {\n ""type"": ""number"",\n ""default"": 30000,\n ""description"": ""Port of the SGLang server""\n },\n ""crowd-pilot.basePath"": {\n ""type"": ""string"",\n ""default"": ""/v1/chat/completions"",\n ""description"": ""Base path for the SGLang API endpoint""\n },\n ""crowd-pilot.modelName"": {\n ""type"": ""string"",\n ""default"": ""qwen/qwen3-8b"",\n ""description"": ""Model name to use for completions""\n },\n ""crowd-pilot.minAvgLogprob"": {\n ""type"": ""number"",\n ""default"": -1.0,\n ""description"": ""Minimum average log-probability per token for displaying suggestions. Higher values (closer to 0) require more confidence. -1.0 ≈ perplexity 2.7""\n },\n ""crowd-pilot.maxContextTokens"": {\n ""type"": ""number"",\n ""default"": 120000,\n ""description"": ""Context length (in tokens). Older messages are truncated to fit. Set below your model's limit to leave room for the response.""\n },\n ""crowd-pilot.enablePreferenceLogging"": {\n ""type"": ""boolean"",\n ""default"": true,\n ""description"": ""Enable logging of accept/reject data for reward model training and RLHF/DPO""\n },\n ""crowd-pilot.preferenceLogPath"": {\n ""type"": ""string"",\n ""default"": """",\n ""description"": ""Custom path for the preference log file (JSONL format). If empty, uses workspace/.crowd-pilot-preferences.jsonl""\n },\n ""crowd-pilot.viewportRadius"": {\n ""type"": ""number"",\n ""default"": 10,\n ""description"": ""Number of lines above/below cursor to include in file viewports""\n }\n }\n },\n ""keybindings"": [\n {\n ""command"": ""crowd-pilot.modelRun"",\n ""key"": ""tab"",\n ""mac"": ""tab"",\n ""when"": ""editorTextFocus && crowdPilot.uiVisible""\n },\n {\n ""command"": ""crowd-pilot.modelRun"",\n ""key"": ""tab"",\n ""mac"": ""tab"",\n ""when"": ""inQuickOpen && crowdPilot.uiVisible""\n },\n {\n ""command"": ""crowd-pilot.hideUi"",\n ""key"": ""escape"",\n ""mac"": ""escape"",\n ""when"": ""crowdPilot.uiVisible""\n },\n {\n ""command"": ""crowd-pilot.showPendingAction"",\n ""key"": ""ctrl+shift+space"",\n ""mac"": ""cmd+shift+space"",\n ""when"": ""terminalFocus && crowdPilot.hasPendingAction""\n }\n ]\n },\n ""scripts"": {\n ""vscode:prepublish"": ""npm run compile"",\n ""compile"": ""tsc -p ./"",\n ""watch"": ""tsc -watch -p ./"",\n ""pretest"": ""npm run compile && npm run lint"",\n ""lint"": ""eslint src"",\n ""test"": ""vscode-test"",\n ""clean"": ""rm -rf out *.tgz"",\n ""clean:all"": ""rm -rf out *.tgz node_modules package-lock.json"",\n ""rebuild-serializer"": ""cd crowd-pilot-serializer/crates/napi && npm install && rm -f index.d.ts index.js && npm run build && npm pack && mv *.tgz ../../../ && cd ../../.. && rm -rf node_modules/@crowd-pilot && npm install""\n },\n ""dependencies"": {\n ""@crowd-pilot/serializer"": ""file:./crowd-pilot-serializer-0.1.0.tgz""\n },\n ""devDependencies"": {\n ""@types/vscode"": ""^1.99.3"",\n ""@types/mocha"": ""^10.0.10"",\n ""@types/node"": ""22.x"",\n ""@typescript-eslint/eslint-plugin"": ""^8.45.0"",\n ""@typescript-eslint/parser"": ""^8.45.0"",\n ""eslint"": ""^9.36.0"",\n ""typescript"": ""^5.9.3"",\n ""@vscode/test-cli"": ""^0.0.11"",\n ""@vscode/test-electron"": ""^2.5.2""\n }\n}\n",json,tab
|
| 3 |
+
2,289,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"5:39:46 PM [info] Activating crowd-code\n5:39:46 PM [info] Recording started\n5:39:46 PM [info] Initializing git provider using file system watchers...\n5:39:46 PM [info] Git repository found\n5:39:46 PM [info] Git provider initialized successfully\n5:39:46 PM [info] Initial git state: [object Object]\n",Log,tab
|
| 4 |
+
3,378,"extension-output-pdoom-org.crowd-code-#1-crowd-code",40,0,"",Log,selection_command
|
| 5 |
+
4,459,"extension-output-pdoom-org.crowd-code-#1-crowd-code",76,0,"",Log,selection_command
|
| 6 |
+
5,1752,"package.json",0,0,"",json,tab
|
| 7 |
+
6,233179,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"",Log,tab
|
| 8 |
+
7,234518,"TERMINAL",0,0,"",,terminal_focus
|
| 9 |
+
8,234519,"package.json",0,0,"",json,tab
|
| 10 |
+
9,264505,"package.json",3829,33," ""mac"": ""cmd+shift+space"",",json,selection_command
|
| 11 |
+
10,266478,"package.json",3833,0,"",json,selection_command
|
| 12 |
+
11,267370,"package.json",3798,0,"",json,selection_command
|
| 13 |
+
12,267481,"package.json",3746,0,"",json,selection_command
|
| 14 |
+
13,267658,"package.json",3798,0,"",json,selection_command
|
| 15 |
+
14,267785,"package.json",3833,0,"",json,selection_command
|
| 16 |
+
15,267960,"package.json",3867,0,"",json,selection_command
|
| 17 |
+
16,268140,"package.json",3833,0,"",json,selection_command
|
| 18 |
+
17,268309,"package.json",3798,0,"",json,selection_command
|
| 19 |
+
18,268868,"package.json",3833,0,"",json,selection_command
|
| 20 |
+
19,272224,"package.json",3798,0,"",json,selection_command
|
| 21 |
+
20,272965,"package.json",3794,34," ""key"": ""ctrl+shift+space"",",json,selection_command
|
| 22 |
+
21,273323,"package.json",3794,68," ""key"": ""ctrl+shift+space"",\n ""mac"": ""cmd+shift+space"",",json,selection_command
|
| 23 |
+
22,291388,"package.json",3833,0,"",json,selection_command
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-4bdfe74d-d330-4df6-b567-868d1f5d15041765303872322-2025_12_09-19.11.17.849/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-4c69dcf8-a147-4975-8e49-6c7ed4761fb81758276984897-2025_09_19-12.16.27.253/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-4dca7453-99f2-409f-9fcb-ea8ac3cd34081767515723494-2026_01_04-15.57.54.263/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-5051ecd3-3076-430b-bdb2-8f2670bf437e1764846717687-2025_12_04-12.12.06.33/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-517cf587-dd37-4da1-93e0-2dbe2eb778af1759393261841-2025_10_02-10.21.12.61/source.csv
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Sequence,Time,File,RangeOffset,RangeLength,Text,Language,Type
|
| 2 |
+
1,2,"slurm/jobs/franz/berlin/coinrun/submission_debug/coinrun_dynamics_base_patch_size_16_action_prepend_cos.sh",0,0,"#!/usr/bin/env bash\n\n#SBATCH --nodes=1\n#SBATCH --ntasks-per-node=1\n#SBATCH --time=24:00:00\n#SBATCH --cpus-per-task=8\n#SBATCH --gres=gpu:1\n#SBATCH --output=/fast/project/HFMI_SynergyUnit/jafar_ws/logs/franz/coinrun/dynamics/%x_%j.log\n#SBATCH --error=/fast/project/HFMI_SynergyUnit/jafar_ws/logs/franz/coinrun/dynamics/%x_%j.log\n#SBATCH --job-name=dynamics_coinrun_mila_submission_patch_size_16_action_prepend_branch_cos_schedule\n#SBATCH --requeue\n#SBATCH --signal=b:usr1@300 # 5 min before timeout\n\n# --- signal trap to requeue job before timeout ---\nrequeue_job() {\n echo ""[$(date)] caught sigusr1 (timeout warning), requeueing slurm job $SLURM_JOB_ID...""\n # optional: trigger checkpoint saving here\n # e.g., touch $checkpoint_dir/requeue_trigger\n scontrol requeue $SLURM_JOB_ID\n exit 0\n}\n\ntrap requeue_job sigusr1\n\n# set checkpoint flag based on restart count\nrestart_count=$(scontrol show job $SLURM_JOB_ID | grep -o 'Restarts=[0-9]*' | cut -d'=' -f2)\n\nif [ $restart_count -eq 0 ]; then\n restore_ckpt_flag=""--no-restore-ckpt""\nelse\n restore_ckpt_flag=""--restore-ckpt""\nfi\n\n\n\n# Log the sbatch script\ncat $0\n\nsource .venv/bin/activate\n\njob_name=$SLURM_JOB_NAME\nslurm_job_id=$SLURM_JOB_ID\n\ntags=""coinrun dynamics 500m_dataset mila_submission debug patch_size_16 action_prepend_branch cos_schedule""\n\narray_records_dir=""/fast/project/HFMI_SynergyUnit/jafar_ws/data/coinrun/array_records_500m_seed_w_increment""\ntokenizer_ckpt_dir=""/fast/project/HFMI_SynergyUnit/jafar_ws/checkpoints/coinrun/tokenizer/tokenizer_coinrun_mila_submission_29736/""\nCHECKPOINT_DIR=""/fast/project/HFMI_SynergyUnit/jafar_ws/checkpoints/coinrun/dynamics/${job_name}/${slurm_job_id}""\nmkdir -p $CHECKPOINT_DIR\n\nenv | grep SLURM\n\ncurrent_branch=$(git rev-parse --abbrev-ref HEAD)\nif [ ""$current_branch"" != ""prepend-action-maskgit"" ]; then\n echo ""This script must be run from the prepend-action-maskgit branch. Current branch is $current_branch. Exiting.""\n exit 1\nfi\n\nsrun python jasmine/train_dynamics.py \\n --lr_schedule=""cos"" \\n --save_ckpt \\n $restore_ckpt_flag \\n --wandb_id $SLURM_JOB_ID \\n --ckpt_dir $CHECKPOINT_DIR \\n --name=""${job_name}_${slurm_job_id}"" \\n --tags ${tags} \\n --entity instant-uv \\n --project jafar \\n --tokenizer_checkpoint=""${tokenizer_ckpt_dir}"" \\n --val_data_dir=""${array_records_dir}/val"" \\n --data_dir=""${array_records_dir}/train"" &\n\nchild_pid=$!\n\nwait $child_pid\n\n",shellscript,tab
|
| 3 |
+
2,235,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"10:21:12 AM [info] Activating crowd-code\n10:21:12 AM [info] Recording started\n10:21:12 AM [info] Initializing git provider using file system watchers...\n",Log,tab
|
| 4 |
+
3,365,"extension-output-pdoom-org.crowd-code-#1-crowd-code",153,0,"10:21:12 AM [info] Git repository found\n10:21:12 AM [info] Git provider initialized successfully\n10:21:12 AM [info] Initial git state: [object Object]\n",Log,content
|
| 5 |
+
4,2260,"TERMINAL",0,0,"",,terminal_command
|
| 6 |
+
5,9493,"TERMINAL",0,0,"",,terminal_command
|
| 7 |
+
6,9770,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",0,0,"#!/usr/bin/env bash\n\n#SBATCH --nodes=1\n#SBATCH --ntasks-per-node=4\n#SBATCH --time=01:00:00\n#SBATCH --partition=accelerated\n#SBATCH --cpus-per-task=5\n#SBATCH --gres=gpu:4\n#SBATCH --output=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/logs/logs_mihir/coinrun/dynamics/sampling/maskgit/%x_%j.log\n#SBATCH --error=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/logs/logs_mihir/coinrun/dynamics/sampling/maskgit/%x_%j.log\n#SBATCH --job-name=coinrun_sample_maskgit\n\n# Activate virtual environment\nsource .venv/bin/activate\n\narray_records_dir=""/fast/project/HFMI_SynergyUnit/jafar_ws/data/coinrun/array_records_500m_seed_w_increment/val""\nCHECKPOINT_PATH=""/fast/project/HFMI_SynergyUnit/jafar_ws/checkpoints/coinrun/dynamics/dynamics_coinrun_mila_submission_patch_size_16_noise_branch/29773""\n--patch_size=16 \\n\n\necho ""Sampling from checkpoint: $CHECKPOINT_PATH""\n\nsrun python jasmine/sample.py \\n --checkpoint $CHECKPOINT_PATH \\n --data_dir=$array_records_dir \\n --seq_len=16 \\n --batch_size=4 \\n --patch_size=16 \\n --start_frame=4 \\n --image_height=64 \\n --image_width=64 \\n --dyna_type=maskgit\n",shellscript,tab
|
| 8 |
+
7,10709,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1132,0,"",shellscript,selection_mouse
|
| 9 |
+
8,13264,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1108,0,"",shellscript,selection_command
|
| 10 |
+
9,14070,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1085,0,"",shellscript,selection_command
|
| 11 |
+
10,14788,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1061,0,"",shellscript,selection_command
|
| 12 |
+
11,14859,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1039,0,"",shellscript,selection_command
|
| 13 |
+
12,14978,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1017,0,"",shellscript,selection_command
|
| 14 |
+
13,15354,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1021,0,"",shellscript,selection_command
|
| 15 |
+
14,15501,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1023,0,"",shellscript,selection_command
|
| 16 |
+
15,15686,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1033,0,"",shellscript,selection_command
|
| 17 |
+
16,16011,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1034,0,"",shellscript,selection_command
|
| 18 |
+
17,16914,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1034,2,"",shellscript,content
|
| 19 |
+
18,17651,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1033,1,"",shellscript,content
|
| 20 |
+
19,18798,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1033,0,"=",shellscript,content
|
| 21 |
+
20,18798,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1034,0,"",shellscript,selection_keyboard
|
| 22 |
+
21,19928,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1034,0,"4",shellscript,content
|
| 23 |
+
22,19929,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1035,0,"",shellscript,selection_keyboard
|
| 24 |
+
23,19931,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1034,0,"",shellscript,selection_command
|
| 25 |
+
24,20438,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1013,0,"",shellscript,selection_command
|
| 26 |
+
25,20443,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",994,0,"",shellscript,selection_command
|
| 27 |
+
26,20469,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",958,0,"",shellscript,selection_command
|
| 28 |
+
27,20535,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",922,0,"",shellscript,selection_command
|
| 29 |
+
28,20537,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",890,0,"",shellscript,selection_command
|
| 30 |
+
29,20565,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",872,0,"",shellscript,selection_command
|
| 31 |
+
30,20595,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",839,0,"",shellscript,selection_command
|
| 32 |
+
31,20637,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",821,0,"",shellscript,selection_command
|
| 33 |
+
32,20664,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",820,0,"",shellscript,selection_command
|
| 34 |
+
33,20699,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",818,0,"",shellscript,selection_command
|
| 35 |
+
34,20866,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",666,0,"",shellscript,selection_command
|
| 36 |
+
35,21115,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",553,0,"",shellscript,selection_command
|
| 37 |
+
36,21404,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",666,0,"",shellscript,selection_command
|
| 38 |
+
37,22357,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",666,134,"",shellscript,content
|
| 39 |
+
38,23132,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",666,0,"/fast/project/HFMI_SynergyUnit/jafar_ws/checkpoints/coinrun/dynamics/dynamics_coinrun_500m_dataset_w_eval_ff/29851",shellscript,content
|
| 40 |
+
39,23132,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",780,0,"",shellscript,selection_keyboard
|
| 41 |
+
40,23708,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",779,0,"",shellscript,selection_command
|
| 42 |
+
41,27818,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",798,0,"",shellscript,selection_command
|
| 43 |
+
42,27980,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",800,0,"",shellscript,selection_command
|
| 44 |
+
43,28156,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",801,0,"",shellscript,selection_command
|
| 45 |
+
44,29058,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",850,0,"",shellscript,selection_command
|
| 46 |
+
45,31485,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",852,0,"",shellscript,selection_command
|
| 47 |
+
46,34063,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",802,0,"",shellscript,selection_command
|
| 48 |
+
47,34306,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",801,0,"",shellscript,selection_command
|
| 49 |
+
48,34331,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",800,0,"",shellscript,selection_command
|
| 50 |
+
49,34373,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",782,0,"",shellscript,selection_command
|
| 51 |
+
50,34398,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",649,0,"",shellscript,selection_command
|
| 52 |
+
51,34425,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",536,0,"",shellscript,selection_command
|
| 53 |
+
52,34464,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",535,0,"",shellscript,selection_command
|
| 54 |
+
53,34516,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",509,0,"",shellscript,selection_command
|
| 55 |
+
54,34524,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",478,0,"",shellscript,selection_command
|
| 56 |
+
55,34558,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",477,0,"",shellscript,selection_command
|
| 57 |
+
56,34595,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",435,0,"",shellscript,selection_command
|
| 58 |
+
57,34632,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",303,0,"",shellscript,selection_command
|
| 59 |
+
58,34684,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",170,0,"",shellscript,selection_command
|
| 60 |
+
59,34694,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",149,0,"",shellscript,selection_command
|
| 61 |
+
60,34718,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",123,0,"",shellscript,selection_command
|
| 62 |
+
61,34767,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",91,0,"",shellscript,selection_command
|
| 63 |
+
62,34799,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",67,0,"",shellscript,selection_command
|
| 64 |
+
63,34825,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",39,0,"",shellscript,selection_command
|
| 65 |
+
64,34874,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",21,0,"",shellscript,selection_command
|
| 66 |
+
65,34914,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",20,0,"",shellscript,selection_command
|
| 67 |
+
66,34923,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",0,0,"",shellscript,selection_command
|
| 68 |
+
67,35251,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",20,0,"",shellscript,selection_command
|
| 69 |
+
68,35495,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",21,0,"",shellscript,selection_command
|
| 70 |
+
69,35519,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",39,0,"",shellscript,selection_command
|
| 71 |
+
70,35560,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",67,0,"",shellscript,selection_command
|
| 72 |
+
71,35597,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",91,0,"",shellscript,selection_command
|
| 73 |
+
72,35661,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",123,0,"",shellscript,selection_command
|
| 74 |
+
73,35661,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",149,0,"",shellscript,selection_command
|
| 75 |
+
74,35690,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",170,0,"",shellscript,selection_command
|
| 76 |
+
75,35728,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",303,0,"",shellscript,selection_command
|
| 77 |
+
76,35763,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",435,0,"",shellscript,selection_command
|
| 78 |
+
77,35808,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",477,0,"",shellscript,selection_command
|
| 79 |
+
78,35837,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",478,0,"",shellscript,selection_command
|
| 80 |
+
79,35858,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",509,0,"",shellscript,selection_command
|
| 81 |
+
80,35907,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",535,0,"",shellscript,selection_command
|
| 82 |
+
81,35950,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",536,0,"",shellscript,selection_command
|
| 83 |
+
82,35979,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",649,0,"",shellscript,selection_command
|
| 84 |
+
83,36016,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",782,0,"",shellscript,selection_command
|
| 85 |
+
84,36025,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",800,0,"",shellscript,selection_command
|
| 86 |
+
85,36205,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",801,0,"",shellscript,selection_command
|
| 87 |
+
86,36508,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",800,0,"",shellscript,selection_command
|
| 88 |
+
87,37208,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"",Log,tab
|
| 89 |
+
88,37824,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",0,0,"",shellscript,tab
|
| 90 |
+
89,40799,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",752,28,"mila_submission_patch_size_16_noise_branch/29773",shellscript,content
|
| 91 |
+
90,40800,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",666,0,"",shellscript,selection_command
|
| 92 |
+
91,41459,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1034,1,"16",shellscript,content
|
| 93 |
+
92,41459,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1034,0,"",shellscript,selection_command
|
| 94 |
+
93,48372,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",1034,2,"4",shellscript,content
|
| 95 |
+
94,48641,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",752,48,"500m_dataset_w_eval_ff/29851",shellscript,content
|
| 96 |
+
95,48642,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",666,0,"",shellscript,selection_command
|
| 97 |
+
96,49583,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",798,0,"",shellscript,selection_command
|
| 98 |
+
97,49963,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",782,18,"",shellscript,content
|
| 99 |
+
98,52928,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",783,0,"",shellscript,selection_command
|
| 100 |
+
99,53071,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",782,0,"",shellscript,selection_command
|
| 101 |
+
100,53274,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",649,0,"",shellscript,selection_command
|
| 102 |
+
101,54467,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",781,0,"",shellscript,selection_command
|
| 103 |
+
102,54950,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",780,0,"",shellscript,selection_command
|
| 104 |
+
103,55387,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",782,0,"",shellscript,selection_command
|
| 105 |
+
104,55888,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",780,0,"",shellscript,selection_command
|
| 106 |
+
105,56208,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",782,0,"",shellscript,selection_command
|
| 107 |
+
106,57506,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"",Log,tab
|
| 108 |
+
107,59575,"TERMINAL",0,0,"",,terminal_focus
|
| 109 |
+
108,59576,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",0,0,"",shellscript,tab
|
| 110 |
+
109,60416,"TERMINAL",0,0,"source /home/franz.srambical/jafar/data/.venv/bin/activate",,terminal_command
|
| 111 |
+
110,60424,"TERMINAL",0,0,"]633;C]0;franz.srambical@hai-login2:~/jafar",,terminal_output
|
| 112 |
+
111,62004,"TERMINAL",0,0,"salloc --gpus=1 --ntasks-per-node=1 --cpus-per-task=10 --mem=100G",,terminal_command
|
| 113 |
+
112,62052,"TERMINAL",0,0,"]633;Csalloc: Granted job allocation 29889\r\n",,terminal_output
|
| 114 |
+
113,62148,"TERMINAL",0,0,"salloc: Waiting for resource configuration\r\n",,terminal_output
|
| 115 |
+
114,63154,"TERMINAL",0,0,"salloc: Nodes hai004 are ready for job\r\n",,terminal_output
|
| 116 |
+
115,63581,"TERMINAL",0,0,"Running inside SLURM, Job ID 29889.\r\n",,terminal_output
|
| 117 |
+
116,63661,"TERMINAL",0,0,"]0;franz.srambical@hai-login2:~/jafar[?2004h[franz.srambical@hai004.haicore.berlin:~/jafar] $ ",,terminal_output
|
| 118 |
+
117,66805,"TERMINAL",0,0,"\r(reverse-i-search)`': [K",,terminal_output
|
| 119 |
+
118,67033,"TERMINAL",0,0,"s': . ""/fast/home/franz.srambical/.cursor-server/bin/3ccce8f55d8cca49f6d28b491a844c699b8719a0/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-bash.[7ms[27mh""",,terminal_output
|
| 120 |
+
119,67127,"TERMINAL",0,0,"[A\r[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[45Pa': [7msa[27mlloc --gpus=1 --ntasks-per-node=1 --cpus-per-task=10 --mem=100G\r\n\r[K[A[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[Cm': bash slurm/dev/franz/berlin/coinrun/sample/maskgit/[7msam[27mple_dynamics_from_fully_trained_tokenizer.sh \r[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[1@p': bash slurm/dev/franz/berlin/coinrun/sample/maskgit/[7msamp[27m",,terminal_output
|
| 121 |
+
120,67338,"TERMINAL",0,0,"\r[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[1@l': bash slurm/dev/franz/berlin/coinrun/sample/maskgit/[7msampl[27m",,terminal_output
|
| 122 |
+
121,67455,"TERMINAL",0,0,"\r[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[1@e': bash slurm/dev/franz/berlin/coinrun/sample/maskgit/[7msample[27m",,terminal_output
|
| 123 |
+
122,68297,"TERMINAL",0,0,"\r[franz.srambical@hai004.haicore.berlin:~/jafar] $ bash slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh [A[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C\r\n\r[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C",,terminal_output
|
| 124 |
+
123,69881,"TERMINAL",0,0,"\r\n[?2004l\rSampling from checkpoint: /fast/project/HFMI_SynergyUnit/jafar_ws/checkpoints/coinrun/dynamics/dynamics_coinrun_500m_dataset_w_eval_ff/29851\r\n",,terminal_output
|
| 125 |
+
124,81875,"TERMINAL",0,0,"/fast/home/franz.srambical/jafar/.venv/lib/python3.13/site-packages/orbax/checkpoint/_src/serialization/type_handlers.py:1269: UserWarning: Sharding info not provided when restoring. Populating sharding info from sharding file. Please note restoration time will be slightly increased due to reading from file. Note also that this option is unsafe when restoring on a different topology than the checkpoint was saved with.\r\n warnings.warn(\r\n",,terminal_output
|
| 126 |
+
125,84455,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",649,0,"",shellscript,selection_command
|
| 127 |
+
126,85127,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",664,0,"",shellscript,selection_command
|
| 128 |
+
127,85387,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",667,0,"",shellscript,selection_command
|
| 129 |
+
128,85417,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",671,0,"",shellscript,selection_command
|
| 130 |
+
129,85437,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",672,0,"",shellscript,selection_command
|
| 131 |
+
130,85475,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",679,0,"",shellscript,selection_command
|
| 132 |
+
131,85496,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",680,0,"",shellscript,selection_command
|
| 133 |
+
132,85556,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",696,0,"",shellscript,selection_command
|
| 134 |
+
133,85575,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",697,0,"",shellscript,selection_command
|
| 135 |
+
134,85615,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",705,0,"",shellscript,selection_command
|
| 136 |
+
135,85656,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",706,0,"",shellscript,selection_command
|
| 137 |
+
136,85676,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",717,0,"",shellscript,selection_command
|
| 138 |
+
137,85715,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",718,0,"",shellscript,selection_command
|
| 139 |
+
138,85735,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",725,0,"",shellscript,selection_command
|
| 140 |
+
139,85775,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",726,0,"",shellscript,selection_command
|
| 141 |
+
140,85807,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",734,0,"",shellscript,selection_command
|
| 142 |
+
141,85847,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",735,0,"",shellscript,selection_command
|
| 143 |
+
142,85895,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",774,0,"",shellscript,selection_command
|
| 144 |
+
143,85915,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",775,0,"",shellscript,selection_command
|
| 145 |
+
144,86107,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",780,0,"",shellscript,selection_command
|
| 146 |
+
145,89715,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",775,0,"",shellscript,selection_command
|
| 147 |
+
146,90055,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",774,0,"",shellscript,selection_command
|
| 148 |
+
147,90195,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",735,0,"",shellscript,selection_command
|
| 149 |
+
148,90455,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",734,0,"",shellscript,selection_command
|
| 150 |
+
149,90915,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",735,0,"",shellscript,selection_command
|
| 151 |
+
150,91875,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",734,0,"",shellscript,selection_command
|
| 152 |
+
151,100396,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",734,1,"v",shellscript,content
|
| 153 |
+
152,100718,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",773,0,"",shellscript,selection_command
|
| 154 |
+
153,105307,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",734,1,"/",shellscript,content
|
| 155 |
+
154,105324,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",734,0,"",shellscript,selection_command
|
| 156 |
+
155,109136,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",734,1,"/",shellscript,selection_command
|
| 157 |
+
156,109616,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",734,40,"/dynamics_coinrun_500m_dataset_w_eval_ff",shellscript,selection_command
|
| 158 |
+
157,110387,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",734,41,"/dynamics_coinrun_500m_dataset_w_eval_ff/",shellscript,selection_command
|
| 159 |
+
158,110687,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",734,46,"/dynamics_coinrun_500m_dataset_w_eval_ff/29851",shellscript,selection_command
|
| 160 |
+
159,111976,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",779,0,"",shellscript,selection_command
|
| 161 |
+
160,112387,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",775,0,"",shellscript,selection_command
|
| 162 |
+
161,112588,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",774,0,"",shellscript,selection_command
|
| 163 |
+
162,112796,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",735,0,"",shellscript,selection_command
|
| 164 |
+
163,113336,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",735,1,"d",shellscript,selection_command
|
| 165 |
+
164,113679,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",735,39,"dynamics_coinrun_500m_dataset_w_eval_ff",shellscript,selection_command
|
| 166 |
+
165,113948,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",735,40,"dynamics_coinrun_500m_dataset_w_eval_ff/",shellscript,selection_command
|
| 167 |
+
166,114308,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",735,45,"dynamics_coinrun_500m_dataset_w_eval_ff/29851",shellscript,selection_command
|
| 168 |
+
167,114747,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",779,0,"",shellscript,selection_command
|
| 169 |
+
168,116616,"TERMINAL",0,0,"",,terminal_command
|
| 170 |
+
169,123348,"TERMINAL",0,0,"Per-frame SSIM:\r\n [0.57319623 0.54733205 0.5227049 0.48956802 0.5013784 0.46939224\r\n 0.4892099 0.47639948 0.44199222 0.46024764 0.49088758 0.44623953]\r\nPer-frame PSNR:\r\n [17.134462 16.30024 15.468311 15.132342 15.414605 15.832775 14.787997\r\n 14.059711 14.086777 14.237678 14.854488 14.458799]\r\nSSIM: 0.4923790395259857\r\nPSNR: 15.14734935760498\r\n",,terminal_output
|
| 171 |
+
170,123976,"TERMINAL",0,0,"W1002 10:23:15.877250 4186569 pjrt_client.cc:1469] WatchJobStateAsync failed for task goo.gle/debugproto job_name: ""jax_worker"": CANCELLED: CANCELLED\r\nAdditional GRPC error information from remote target coordination_service while calling /tensorflow.CoordinationService/WatchJobState:\r\n:UNKNOWN:Error received from peer {grpc_status:1, grpc_message:""CANCELLED""} [type.googleapis.com/tensorflow.DerivedStatus='']\r\n",,terminal_output
|
| 172 |
+
171,124628,"TERMINAL",0,0,"]0;franz.srambical@hai-login2:~/jafar[?2004h[franz.srambical@hai004.haicore.berlin:~/jafar] $ ",,terminal_output
|
| 173 |
+
172,167574,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",0,0,"",shellscript,tab
|
| 174 |
+
173,236650,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",782,0,"",shellscript,selection_command
|
| 175 |
+
174,354192,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",779,0,"",shellscript,selection_command
|
| 176 |
+
175,354344,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",780,0,"",shellscript,selection_command
|
| 177 |
+
176,354540,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",782,0,"",shellscript,selection_command
|
| 178 |
+
177,355406,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",649,0,"",shellscript,selection_command
|
| 179 |
+
178,355579,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",664,0,"",shellscript,selection_command
|
| 180 |
+
179,355789,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",667,0,"",shellscript,selection_command
|
| 181 |
+
180,356658,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",666,114,"",shellscript,content
|
| 182 |
+
181,357202,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",666,0,"""/fast/project/HFMI_SynergyUnit/jafar_ws/checkpoints/coinrun/dynamics/dynamics_coinrun_500m_dataset/29519""",shellscript,content
|
| 183 |
+
182,357202,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",772,0,"",shellscript,selection_keyboard
|
| 184 |
+
183,357877,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",771,0,"",shellscript,selection_command
|
| 185 |
+
184,358490,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",774,0,"",shellscript,selection_command
|
| 186 |
+
185,361343,"TERMINAL",0,0,"\r[K[franz.srambical@hai004.haicore.berlin:~/jafar] $ ",,terminal_output
|
| 187 |
+
186,362006,"TERMINAL",0,0,"bash slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh ",,terminal_output
|
| 188 |
+
187,362578,"TERMINAL",0,0,"\r\n[?2004l\rSampling from checkpoint: /fast/project/HFMI_SynergyUnit/jafar_ws/checkpoints/coinrun/dynamics/dynamics_coinrun_500m_dataset/29519\r\n",,terminal_output
|
| 189 |
+
188,374472,"TERMINAL",0,0,"/fast/home/franz.srambical/jafar/.venv/lib/python3.13/site-packages/orbax/checkpoint/_src/serialization/type_handlers.py:1269: UserWarning: Sharding info not provided when restoring. Populating sharding info from sharding file. Please note restoration time will be slightly increased due to reading from file. Note also that this option is unsafe when restoring on a different topology than the checkpoint was saved with.\r\n warnings.warn(\r\n",,terminal_output
|
| 190 |
+
189,383802,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",649,0,"",shellscript,selection_command
|
| 191 |
+
190,384086,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",664,0,"",shellscript,selection_command
|
| 192 |
+
191,384236,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",668,0,"",shellscript,selection_command
|
| 193 |
+
192,384420,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",672,0,"",shellscript,selection_command
|
| 194 |
+
193,384584,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",673,0,"",shellscript,selection_command
|
| 195 |
+
194,384835,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",680,0,"",shellscript,selection_command
|
| 196 |
+
195,384867,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",681,0,"",shellscript,selection_command
|
| 197 |
+
196,384919,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",697,0,"",shellscript,selection_command
|
| 198 |
+
197,384946,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",698,0,"",shellscript,selection_command
|
| 199 |
+
198,384978,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",706,0,"",shellscript,selection_command
|
| 200 |
+
199,384996,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",707,0,"",shellscript,selection_command
|
| 201 |
+
200,385110,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",718,0,"",shellscript,selection_command
|
| 202 |
+
201,385296,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",719,0,"",shellscript,selection_command
|
| 203 |
+
202,385426,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",726,0,"",shellscript,selection_command
|
| 204 |
+
203,385575,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",727,0,"",shellscript,selection_command
|
| 205 |
+
204,385764,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",735,0,"",shellscript,selection_command
|
| 206 |
+
205,385912,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",736,0,"",shellscript,selection_command
|
| 207 |
+
206,387774,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",736,1,"d",shellscript,selection_command
|
| 208 |
+
207,387994,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",736,29,"dynamics_coinrun_500m_dataset",shellscript,selection_command
|
| 209 |
+
208,388198,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",736,30,"dynamics_coinrun_500m_dataset/",shellscript,selection_command
|
| 210 |
+
209,388499,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",736,35,"dynamics_coinrun_500m_dataset/29519",shellscript,selection_command
|
| 211 |
+
210,389158,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",770,0,"",shellscript,selection_command
|
| 212 |
+
211,415304,"TERMINAL",0,0,"Per-frame SSIM:\r\n [0.5646278 0.6038726 0.5279748 0.5055892 0.49214277 0.47423407\r\n 0.45490086 0.4486615 0.39024955 0.4109726 0.44856626 0.43377078]\r\nPer-frame PSNR:\r\n [18.160048 16.95538 15.633233 15.407247 15.042919 14.729964 14.036336\r\n 13.592623 13.456531 13.609724 14.187572 14.492484]\r\nSSIM: 0.4796302318572998\r\nPSNR: 14.942004203796387\r\n",,terminal_output
|
| 213 |
+
212,416062,"TERMINAL",0,0,"W1002 10:28:07.966836 135844 pjrt_client.cc:1469] WatchJobStateAsync failed for task goo.gle/debugonly job_name: ""jax_worker"": UNAVAILABLE: failed to connect to all addresses; last error: UNKNOWN: ipv4:10.86.2.40:62657: Failed to connect to remote host: Connection refused\r\nAdditional GRPC error information from remote target coordination_service while calling /tensorflow.CoordinationService/WatchJobState:\r\n:UNKNOWN:Error received from peer {grpc_status:14, grpc_message:""failed to connect to all addresses; last error: UNKNOWN: ipv4:10.86.2.40:62657: Failed to connect to remote host: Connection refused""}\r\n",,terminal_output
|
| 214 |
+
213,416747,"TERMINAL",0,0,"]0;franz.srambical@hai-login2:~/jafar[?2004h[franz.srambical@hai004.haicore.berlin:~/jafar] $ ",,terminal_output
|
| 215 |
+
214,425264,"TERMINAL",0,0,"\r[K[franz.srambical@hai004.haicore.berlin:~/jafar] $ ",,terminal_output
|
| 216 |
+
215,426032,"TERMINAL",0,0,"\r[K[franz.srambical@hai004.haicore.berlin:~/jafar] $ ",,terminal_output
|
| 217 |
+
216,435832,"slurm/dev/franz/berlin/coinrun/sample/maskgit/sample_dynamics_from_fully_trained_tokenizer.sh",0,0,"",shellscript,tab
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-53d91009-6945-47d9-96a4-938a0ca5e66c1758023129511-2025_09_16-13.45.36.509/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-5bd2220b-fd06-4957-ae02-02d699413f701762612130038-2025_11_08-15.28.56.621/source.csv
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Sequence,Time,File,RangeOffset,RangeLength,Text,Language,Type
|
| 2 |
+
1,207,"Untitled-2",0,0,"",plaintext,tab
|
| 3 |
+
2,249,"Untitled-1",0,0,"",plaintext,tab
|
| 4 |
+
3,418,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"3:28:56 PM [info] Activating crowd-code\n3:28:56 PM [info] Recording started\n3:28:56 PM [info] Initializing git provider using file system watchers...\n3:28:56 PM [info] No workspace folder found\n",Log,tab
|
| 5 |
+
4,1460,"Untitled-1",0,0,"",plaintext,tab
|
| 6 |
+
5,7192,"Untitled-1",0,0,"Hello, world!",plaintext,content
|
| 7 |
+
6,8063,"Untitled-1",12,0,"",plaintext,selection_command
|
| 8 |
+
7,8227,"Untitled-1",7,0,"",plaintext,selection_command
|
| 9 |
+
8,8348,"Untitled-1",5,0,"",plaintext,selection_command
|
| 10 |
+
9,8512,"Untitled-1",0,0,"",plaintext,selection_command
|
| 11 |
+
10,9283,"Untitled-1",5,0,"",plaintext,selection_command
|
| 12 |
+
11,9733,"Untitled-1",7,0,"",plaintext,selection_command
|
| 13 |
+
12,10240,"Untitled-1",7,6,"",plaintext,content
|
| 14 |
+
13,10348,"Untitled-1",7,0,"m",plaintext,content
|
| 15 |
+
14,10350,"Untitled-1",8,0,"",plaintext,selection_keyboard
|
| 16 |
+
15,10540,"Untitled-1",8,0,"y",plaintext,content
|
| 17 |
+
16,10541,"Untitled-1",9,0,"",plaintext,selection_keyboard
|
| 18 |
+
17,10692,"Untitled-1",9,0," ",plaintext,content
|
| 19 |
+
18,10694,"Untitled-1",10,0,"",plaintext,selection_keyboard
|
| 20 |
+
19,10717,"Untitled-1",10,0,"n",plaintext,content
|
| 21 |
+
20,10718,"Untitled-1",11,0,"",plaintext,selection_keyboard
|
| 22 |
+
21,10902,"Untitled-1",11,0,"a",plaintext,content
|
| 23 |
+
22,10903,"Untitled-1",12,0,"",plaintext,selection_keyboard
|
| 24 |
+
23,10914,"Untitled-1",12,0,"m",plaintext,content
|
| 25 |
+
24,10915,"Untitled-1",13,0,"",plaintext,selection_keyboard
|
| 26 |
+
25,10958,"Untitled-1",13,0,"e",plaintext,content
|
| 27 |
+
26,10960,"Untitled-1",14,0,"",plaintext,selection_keyboard
|
| 28 |
+
27,11133,"Untitled-1",14,0," ",plaintext,content
|
| 29 |
+
28,11134,"Untitled-1",15,0,"",plaintext,selection_keyboard
|
| 30 |
+
29,11145,"Untitled-1",15,0,"i",plaintext,content
|
| 31 |
+
30,11146,"Untitled-1",16,0,"",plaintext,selection_keyboard
|
| 32 |
+
31,11304,"Untitled-1",16,0,"s",plaintext,content
|
| 33 |
+
32,11305,"Untitled-1",17,0,"",plaintext,selection_keyboard
|
| 34 |
+
33,11350,"Untitled-1",17,0," ",plaintext,content
|
| 35 |
+
34,11351,"Untitled-1",18,0,"",plaintext,selection_keyboard
|
| 36 |
+
35,11607,"Untitled-1",18,0,"Ryan and I'm a software engineer.",plaintext,content
|
| 37 |
+
36,12271,"Untitled-1",50,0,"",plaintext,selection_command
|
| 38 |
+
37,12399,"Untitled-1",42,0,"",plaintext,selection_command
|
| 39 |
+
38,12653,"Untitled-1",33,0,"",plaintext,selection_command
|
| 40 |
+
39,12685,"Untitled-1",31,0,"",plaintext,selection_command
|
| 41 |
+
40,12720,"Untitled-1",29,0,"",plaintext,selection_command
|
| 42 |
+
41,12750,"Untitled-1",28,0,"",plaintext,selection_command
|
| 43 |
+
42,12959,"Untitled-1",27,0,"",plaintext,selection_command
|
| 44 |
+
43,13073,"Untitled-1",23,0,"",plaintext,selection_command
|
| 45 |
+
44,13238,"Untitled-1",18,0,"",plaintext,selection_command
|
| 46 |
+
45,13779,"Untitled-1",18,33,"",plaintext,content
|
| 47 |
+
46,22888,"Untitled-1",18,0,"a",plaintext,content
|
| 48 |
+
47,22889,"Untitled-1",19,0,"",plaintext,selection_keyboard
|
| 49 |
+
48,22892,"Untitled-1",19,0,"n",plaintext,content
|
| 50 |
+
49,22893,"Untitled-1",20,0,"",plaintext,selection_keyboard
|
| 51 |
+
50,23139,"Untitled-1",20,0," ",plaintext,content
|
| 52 |
+
51,23141,"Untitled-1",21,0,"",plaintext,selection_keyboard
|
| 53 |
+
52,23204,"Untitled-1",21,0,"i",plaintext,content
|
| 54 |
+
53,23205,"Untitled-1",22,0,"",plaintext,selection_keyboard
|
| 55 |
+
54,23565,"Untitled-1",21,1,"",plaintext,content
|
| 56 |
+
55,23765,"Untitled-1",20,1,"",plaintext,content
|
| 57 |
+
56,23889,"Untitled-1",20,0,"d",plaintext,content
|
| 58 |
+
57,23890,"Untitled-1",21,0,"",plaintext,selection_keyboard
|
| 59 |
+
58,23964,"Untitled-1",21,0," ",plaintext,content
|
| 60 |
+
59,23965,"Untitled-1",22,0,"",plaintext,selection_keyboard
|
| 61 |
+
60,24269,"Untitled-1",18,4,"",plaintext,content
|
| 62 |
+
61,24430,"Untitled-1",15,3,"",plaintext,content
|
| 63 |
+
62,24566,"Untitled-1",10,5,"",plaintext,content
|
| 64 |
+
63,24729,"Untitled-1",7,3,"",plaintext,content
|
| 65 |
+
64,24869,"Untitled-1",5,2,"",plaintext,content
|
| 66 |
+
65,25031,"Untitled-1",0,5,"",plaintext,content
|
| 67 |
+
66,25263,"Untitled-1",0,0,"f",plaintext,content
|
| 68 |
+
67,25265,"Untitled-1",1,0,"",plaintext,selection_keyboard
|
| 69 |
+
68,25307,"Untitled-1",1,0,"o",plaintext,content
|
| 70 |
+
69,25308,"Untitled-1",2,0,"",plaintext,selection_keyboard
|
| 71 |
+
70,25433,"Untitled-1",2,0,"r",plaintext,content
|
| 72 |
+
71,25434,"Untitled-1",3,0,"",plaintext,selection_keyboard
|
| 73 |
+
72,25661,"Untitled-1",3,0," ",plaintext,content
|
| 74 |
+
73,25663,"Untitled-1",4,0,"",plaintext,selection_keyboard
|
| 75 |
+
74,25750,"Untitled-1",4,0,"i",plaintext,content
|
| 76 |
+
75,25752,"Untitled-1",5,0,"",plaintext,selection_keyboard
|
| 77 |
+
76,25897,"Untitled-1",5,0," ",plaintext,content
|
| 78 |
+
77,26097,"Untitled-1",6,0,"i",plaintext,content
|
| 79 |
+
78,26099,"Untitled-1",7,0,"",plaintext,selection_keyboard
|
| 80 |
+
79,26188,"Untitled-1",7,0,"n",plaintext,content
|
| 81 |
+
80,26190,"Untitled-1",8,0,"",plaintext,selection_keyboard
|
| 82 |
+
81,26334,"Untitled-1",8,0," ",plaintext,content
|
| 83 |
+
82,26336,"Untitled-1",9,0,"",plaintext,selection_keyboard
|
| 84 |
+
83,27749,"Untitled-1",8,0,"",plaintext,selection_command
|
| 85 |
+
84,28347,"Untitled-1",9,0,"",plaintext,selection_command
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-5f48c907-14e5-4011-960f-0c7da6e16d1c1755864806800-2025_08_22-14.13.40.52/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-6061119e-3f80-4137-8240-2452a9d7dd541755784835236-2025_08_21-16.00.55.612/source.csv
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Sequence,Time,File,RangeOffset,RangeLength,Text,Language,Type
|
| 2 |
+
1,2,"MaxText/checkpointing.py",0,0,"# Copyright 2023–2025 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the ""License"");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an ""AS IS"" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n""""""Create an Orbax CheckpointManager with specified (Async or not) Checkpointer.""""""\n\nimport time\nfrom typing import Any\n\nfrom absl import flags\nfrom etils import epath\nfrom flax.training import train_state\nimport grain.python as grain\nimport jax\nfrom MaxText import exceptions\nfrom MaxText import max_logging\nfrom MaxText.globals import DEFAULT_OCDBT_TARGET_DATA_FILE_SIZE\nfrom MaxText.multihost_dataloading import MultiHostDataLoadIterator\nimport numpy as np\nimport orbax.checkpoint as ocp\nfrom orbax.checkpoint import v1 as ocp_v1\nimport orbax.checkpoint.experimental.emergency.checkpoint_manager as emergency_checkpoint_manager\nimport orbax.checkpoint.experimental.emergency.replicator_checkpoint_manager as emergency_replicator_checkpoint_manager\n# pylint: disable=too-many-positional-arguments\n\nCheckpointManager = ocp.CheckpointManager\nCheckpointManagerOptions = ocp.CheckpointManagerOptions\nComposite = ocp.args.Composite\nPyTreeCheckpointHandler = ocp.PyTreeCheckpointHandler\nEmergencyCheckpointManager = emergency_checkpoint_manager.CheckpointManager\nLocalCheckpointOptions = emergency_checkpoint_manager.LocalCheckpointOptions\nPersistentCheckpointOptions = emergency_checkpoint_manager.PersistentCheckpointOptions\nEmergencyReplicatorCheckpointManager = emergency_replicator_checkpoint_manager.ReplicatorCheckpointManager\n\n\ndef _load_full_state_from_path(\n path,\n abstract_unboxed_pre_state,\n enable_orbax_v1,\n checkpoint_conversion_fn,\n source_checkpoint_layout,\n):\n """"""Load full state from checkpoint at specified path.\n\n Args:\n path: path to checkpoint\n abstract_unboxed_pre_state: an abstract state that Orbax matches type\n against.\n enable_orbax_v1: whether to use orbax v1 or the previously supported v0.\n checkpoint_conversion_fn: user-provided function to convert checkpoint to\n maxtext-supported state.\n source_checkpoint_layout: String representation of the checkpoint layout\n of the source checkpoint.\n\n Returns:\n The loaded state.\n """"""\n\n if enable_orbax_v1:\n if source_checkpoint_layout == ""orbax"":\n context = ocp_v1.Context(checkpoint_layout=ocp_v1.options.CheckpointLayout.ORBAX)\n elif source_checkpoint_layout == ""safetensors"":\n context = ocp_v1.Context(checkpoint_layout=ocp_v1.options.CheckpointLayout.SAFETENSORS)\n else:\n raise ocp_v1.errors.InvalidLayoutError(f""Unknown checkpoint layout: {source_checkpoint_layout}"")\n if ocp_v1.is_orbax_checkpoint(path):\n state = ocp_v1.load_pytree(path, abstract_unboxed_pre_state)\n else:\n with context:\n pre_transformed_state = ocp_v1.load_pytree(path)\n state = checkpoint_conversion_fn(pre_transformed_state)\n # TODO(zachmeyers): Add call to place on devices, after sharding logic\n # is implemented on Orbax side.\n return state\n else:\n # This is the original v0 logic that should be restored. For the edge case\n # where a CheckpointManager is present but empty.\n p = epath.Path(path)\n return ocp.StandardCheckpointer().restore(p, abstract_unboxed_pre_state)\n\n\ndef create_orbax_checkpoint_manager(\n checkpoint_dir: str,\n enable_checkpointing: bool,\n use_async: bool,\n save_interval_steps: int,\n dataset_type: None | str = ""tfds"",\n orbax_logger: Any = None, # pytype: disable=attribute-error\n use_ocdbt: bool = True,\n use_zarr3: bool = True,\n):\n """"""Returns specified Orbax (async or not) CheckpointManager or None if checkpointing is disabled.""""""\n if not enable_checkpointing:\n max_logging.log(""Checkpointing disabled, not creating checkpoint manager."")\n return None\n\n max_logging.log(f""Creating checkpoint manager with ocdbt={use_ocdbt} and zarr3={use_zarr3}"")\n\n if dataset_type == ""grain"":\n item_names = (""items"", ""iter"")\n else:\n item_names = (""items"",)\n\n # local storage checkpoint needs parent directory created\n p = epath.Path(checkpoint_dir)\n p.mkdir(exist_ok=True, parents=True)\n # we need to use ocdbt and zarr3 to control max file size in the checkpoint\n # omitting `iter` uses default handler for `iter`\n item_handlers = {""items"": PyTreeCheckpointHandler(use_ocdbt=use_ocdbt, use_zarr3=use_zarr3)}\n manager = CheckpointManager(\n p,\n item_names=item_names,\n item_handlers=item_handlers,\n options=CheckpointManagerOptions(\n create=True,\n save_interval_steps=save_interval_steps,\n enable_async_checkpointing=use_async,\n ),\n logger=orbax_logger,\n )\n\n max_logging.log(""Checkpoint manager created!"")\n return manager\n\n\ndef create_orbax_emergency_checkpoint_manager(\n local_checkpoint_dir: str,\n persistent_checkpoint_dir: str,\n global_mesh: jax.sharding.Mesh,\n abstract_state: Any,\n local_save_interval_steps: int,\n persistent_save_interval_steps: int,\n orbax_logger: Any = None, # pytype: disable=attribute-error\n):\n """"""Returns an emergency checkpoint manager.""""""\n flags.FLAGS.experimental_orbax_use_distributed_process_id = True\n max_logging.log(""Creating emergency checkpoint manager..."")\n\n # Only create directories if running on GPUs as the previous\n # directory structure might be assumed by TPUs\n if global_mesh.devices.flatten()[0].platform == ""gpu"":\n # pylint: disable=protected-access\n local_checkpoint_dir = f""{local_checkpoint_dir}/{jax._src.distributed.global_state.process_id}""\n local_p = epath.Path(local_checkpoint_dir)\n persistent_p = epath.Path(persistent_checkpoint_dir)\n local_p.mkdir(exist_ok=True, parents=True)\n persistent_p.mkdir(exist_ok=True, parents=True)\n\n manager = EmergencyCheckpointManager(\n local_checkpoint_dir,\n epath.Path(persistent_checkpoint_dir),\n global_mesh=global_mesh,\n abstract_state=abstract_state,\n options=emergency_checkpoint_manager.CheckpointManagerOptions(\n local=LocalCheckpointOptions(save_interval_steps=local_save_interval_steps),\n persistent=PersistentCheckpointOptions(save_interval_steps=persistent_save_interval_steps),\n ),\n logger=orbax_logger,\n )\n\n max_logging.log(""Emergency checkpoint manager created!"")\n return manager\n\n\ndef create_orbax_emergency_replicator_checkpoint_manager(\n local_checkpoint_dir: str,\n save_interval_steps: int,\n global_mesh: jax.sharding.Mesh,\n):\n """"""Returns an emergency replicator checkpoint manager.""""""\n flags.FLAGS.experimental_orbax_use_distributed_process_id = True\n max_logging.log(""Creating emergency replicator checkpoint manager..."")\n\n manager = EmergencyReplicatorCheckpointManager(\n epath.Path(local_checkpoint_dir),\n options=emergency_replicator_checkpoint_manager.ReplicatorCheckpointManagerOptions(\n save_interval_steps=save_interval_steps,\n ),\n global_mesh=global_mesh,\n )\n\n max_logging.log(""Emergency replicator checkpoint manager created!"")\n return manager\n\n\ndef replicator_error_handler(config: Any):\n """"""Replicator error handler to handle errors in replicator service.""""""\n if config.enable_emergency_checkpoint and config.use_replicator_service and config.local_checkpoint_directory:\n local_dir = config.local_checkpoint_directory\n replicator_errors_file = f""{local_dir}/replicator.errors""\n replicator_failed_file = f""{local_dir}/replicator.failed""\n process_replicator_error_file(replicator_errors_file)\n\n # if the replicator.failed file exists, then we have a fatal error\n is_fatal = process_replicator_error_file(replicator_failed_file)\n if is_fatal:\n raise ValueError(""Replicator fatal error found in replicator.failed file."")\n\n\ndef process_replicator_error_file(error_file: str) -> bool:\n """"""Handles replicator errors by reading, logging, cleaning the error file.""""""\n error_file_path_exists = epath.Path(error_file).exists()\n if error_file_path_exists:\n max_logging.log(f""replicator_error_handler: file found: {error_file}."")\n read_replicator_error_file(error_file)\n cleanup_replicator_error_file(error_file)\n\n return error_file_path_exists\n\n\ndef read_replicator_error_file(error_file: str):\n """"""Read replicator errors file.""""""\n try:\n error_data = epath.Path(error_file).read_text()\n max_logging.log(f""Contents of replicator error file:\n{error_data}"")\n except (OSError, ValueError) as e:\n max_logging.log(""replicator_error_handler: Failed to read contents of failed"" f"" file: {e}"")\n\n\ndef cleanup_replicator_error_file(error_file: str):\n """"""Clean up replicator errors file.""""""\n try:\n epath.Path(error_file).unlink()\n except (OSError, ValueError) as e:\n max_logging.log(""replicator_error_handler: Failed to remove replicator errors file:"" f"" {e}"")\n\n\ndef print_save_message(step, async_checkpointing):\n if async_checkpointing:\n max_logging.log(f""Started an asynchronous checkpoint save for step {step}"")\n else:\n max_logging.log(f""Saved a checkpoint at step {step}."")\n\n\ndef _find_idx(array: np.ndarray, replica_axis_idx: int):\n """"""Returns the index along given dimension that the current host belongs to.""""""\n idx = None\n for idx, val in np.ndenumerate(array):\n if val.process_index == jax.process_index():\n break\n return idx[replica_axis_idx]\n\n\ndef _replica_devices(device_array: np.ndarray, replica_axis_idx: int):\n """"""Returns the devices from the replica that current host belongs to.\n\n Replicas are assumed to be restricted to the first axis.\n\n Args:\n device_array: devices of the mesh that can be obtained by mesh.devices()\n replica_axis_idx: axis dimension along which replica is taken\n\n Returns:\n devices inside the replica that current host is in\n """"""\n idx = _find_idx(device_array, replica_axis_idx)\n replica_result = np.take(device_array, idx, axis=replica_axis_idx)\n return np.expand_dims(replica_result, axis=replica_axis_idx)\n\n\ndef load_state_if_possible(\n checkpoint_manager: CheckpointManager | None,\n data_iterator: MultiHostDataLoadIterator | None,\n load_parameters_from_path: str,\n load_full_state_from_path: str,\n checkpoint_storage_concurrent_gb: int,\n abstract_unboxed_pre_state: train_state.TrainState,\n enable_single_replica_ckpt_restoring: bool | None = False,\n dataset_type: str | None = ""tfds"",\n step: int = -1, # -1 means latest\n use_ocdbt=True,\n use_zarr3=True,\n enable_orbax_v1=False,\n checkpoint_conversion_fn=None,\n source_checkpoint_layout=""orbax"",\n):\n """"""Loads TrainState as possible from the inputs.\n\n Args:\n checkpoint_manager: if the checkpoint_manager has a valid checkpoint, return\n that TrainState. This enables a full reload of a run in progress.\n load_parameters_from_path: if there is no checkpoint in the checkpoint\n manager, load parameters from a parameter only checkpoint at this path.\n load_full_state_from_path: if there is no checkpoint in the checkpoint\n manager, load full state from a full state checkpoint at this path.\n abstract_unboxed_pre_state: an unboxed, abstract TrainState that Orbax\n matches type against.\n enable_single_replica_ckpt_restoring: bool flag for restoring checkpoitn\n with SingleReplicaArrayHandler\n checkpoint_storage_concurrent_gb: concurrent GB for checkpoint byte I/O.\n enable_orbax_v1: bool flag for enabling Orbax v1.\n checkpoint_conversion_fn: function for converting checkpoint to Orbax v1.\n source_checkpoint_layout: Optional checkpoint context to use for loading,\n provided in string format with the default being ""orbax"".\n\n Returns:\n A tuple of (train_state, train_state_params) where full_train_state captures\n a full reload and train_state_params just the params for a partial reload.\n At most one will be non-None. Both can be None if neither checkpoint is\n set.\n """"""\n\n if checkpoint_manager is not None:\n max_logging.log(""checkpoint manager exists so trying to load this run's existing checkpoint"")\n\n step = checkpoint_manager.latest_step() if step < 0 else step\n if step is not None:\n max_logging.log(f""restoring from this run's directory step {step}"")\n\n def map_to_pspec(data):\n if not enable_single_replica_ckpt_restoring:\n return ocp.type_handlers.ArrayRestoreArgs(sharding=data.sharding)\n pspec = data.sharding.spec\n mesh = data.sharding.mesh\n replica_axis_index = 0\n replica_devices = _replica_devices(mesh.devices, replica_axis_index)\n replica_mesh = jax.sharding.Mesh(replica_devices, mesh.axis_names)\n single_replica_sharding = jax.sharding.NamedSharding(replica_mesh, pspec)\n\n return ocp.type_handlers.SingleReplicaArrayRestoreArgs(\n sharding=jax.sharding.NamedSharding(mesh, pspec),\n single_replica_sharding=single_replica_sharding,\n global_shape=data.shape,\n dtype=data.dtype,\n )\n\n if enable_single_replica_ckpt_restoring:\n array_handler = ocp.type_handlers.SingleReplicaArrayHandler(\n replica_axis_index=0,\n broadcast_memory_limit_bytes=1024 * 1024 * 1000, # 1000 MB limit\n )\n ocp.type_handlers.register_type_handler(jax.Array, array_handler, override=True)\n\n restore_args = jax.tree_util.tree_map(map_to_pspec, abstract_unboxed_pre_state)\n checkpoint_args = ocp.args.PyTreeRestore(item=abstract_unboxed_pre_state, restore_args=restore_args)\n\n match (checkpoint_manager, dataset_type, data_iterator):\n # Case 1: Matches if 'checkpoint_manager' is an instance of either EmergencyCheckpointManager\n # or EmergencyReplicatorCheckpointManager. The '_' indicates that 'dataset_type' and\n # 'data_iterator' can be any value and aren't used in this pattern.\n case (checkpoint_manager, _, _) if isinstance(\n checkpoint_manager, (EmergencyCheckpointManager, EmergencyReplicatorCheckpointManager)\n ):\n return (checkpoint_manager.restore(step, args=Composite(state=checkpoint_args)).state, None)\n # Case 2: Matches if dataset type is ""grain"" and a specific checkpoint file exits for the iterator\n # exists within the checkpoint manager's directory for the given step.\n case (checkpoint_manager, dataset_type, data_iterator) if dataset_type == ""grain"" and data_iterator and (\n checkpoint_manager.directory / str(step) / ""iter""\n ).exists():\n grain_iter = grain.PyGrainCheckpointRestore(data_iterator.local_iterator)\n return (checkpoint_manager.restore(step, args=Composite(items=checkpoint_args, iter=grain_iter)), None)\n # Case 3: Default/Fallback case.\n # This case acts as a wildcard ('_') and matches if none of the preceding cases were met.\n case _:\n return (checkpoint_manager.restore(step, args=Composite(items=checkpoint_args)), None)\n\n if load_parameters_from_path != """":\n restored_params = load_params_from_path(\n load_parameters_from_path,\n abstract_unboxed_pre_state.params,\n checkpoint_storage_concurrent_gb,\n use_ocdbt=use_ocdbt,\n use_zarr3=use_zarr3,\n )\n return None, restored_params\n elif load_full_state_from_path != """":\n max_logging.log(f""Loading full state from path: {load_full_state_from_path}"")\n restored_state = _load_full_state_from_path(\n path=load_full_state_from_path,\n abstract_unboxed_pre_state=abstract_unboxed_pre_state,\n enable_orbax_v1=enable_orbax_v1,\n checkpoint_conversion_fn=checkpoint_conversion_fn,\n source_checkpoint_layout=source_checkpoint_layout,\n )\n return {""items"": restored_state}, None\n else:\n max_logging.log(""No existing checkpoints found, not restoring checkpoint."")\n return None, None\n\n\ndef setup_checkpoint_logger(config) -> Any | None: # pytype: disable=attribute-error\n """"""Setup checkpoint logger.\n Args:\n config\n Returns:\n CloudLogger\n """"""\n orbax_cloud_logger = None\n max_logging.log(""Setting up checkpoint logger..."")\n if config.enable_checkpoint_cloud_logger:\n logger_name = f""goodput_{config.run_name}""\n orbax_cloud_logger = ocp.logging.CloudLogger(\n options=ocp.logging.CloudLoggerOptions(job_name=config.run_name, logger_name=logger_name)\n )\n max_logging.log(""Successfully set up checkpoint cloud logger."")\n\n return orbax_cloud_logger\n\n\ndef load_params_from_path(\n load_parameters_from_path, abstract_unboxed_params, checkpoint_storage_concurrent_gb, use_ocdbt=True, use_zarr3=True\n):\n """"""Load decode params from checkpoint at specified path.""""""\n assert load_parameters_from_path, ""load_parameters_from_path is not defined.""\n max_logging.log(f""restoring params from {load_parameters_from_path}"")\n\n # *_concurrent_gb should be set for large models, the default is 96.\n max_logging.log(f""Creating checkpoint manager with ocdbt={use_ocdbt} and zarr3={use_zarr3}"")\n ckptr = ocp.Checkpointer(\n ocp.PyTreeCheckpointHandler(\n restore_concurrent_gb=checkpoint_storage_concurrent_gb,\n save_concurrent_gb=checkpoint_storage_concurrent_gb,\n use_ocdbt=use_ocdbt,\n use_zarr3=use_zarr3,\n )\n )\n\n # This is a memory optimization. We don't want to restore the entire checkpoint - only the params.\n # Rather than pass the entire abstract state, which could unnecessarily restore opt_state and such and waste\n # memory, we instead specify here that we are just restoring the params field of the checkpoint\n # (which itself may be a dictionary containing a key named 'params').\n restore_args = ocp.checkpoint_utils.construct_restore_args(abstract_unboxed_params)\n restored = ckptr.restore(\n epath.Path(load_parameters_from_path),\n item={""params"": abstract_unboxed_params},\n transforms={},\n restore_args={""params"": restore_args},\n )\n return restored[""params""]\n\n\ndef save_params_to_path(checkpoint_dir, params, use_ocdbt=True, use_zarr3=True):\n """"""Save decode params in checkpoint at specified path.""""""\n assert checkpoint_dir, ""checkpoint_dir is not defined.""\n print(f""Saving quantized params checkpoint with use_ocdbt = {use_ocdbt} and use_zarr3 = {use_zarr3}"")\n orbax_checkpointer = ocp.PyTreeCheckpointer(use_ocdbt=use_ocdbt, use_zarr3=use_zarr3)\n orbax_checkpointer.save(checkpoint_dir, {""params"": params}, force=True)\n print(f""Quantized params checkpoint saved at: {checkpoint_dir}"")\n\n\ndef maybe_save_checkpoint(checkpoint_manager, state, config, data_iterator, step=None):\n """"""Save checkpoint if checkpointing is enabled.""""""\n if checkpoint_manager is None:\n return\n\n # Determine the effective step for saving a checkpoint.\n # If 'step' is not provided, this call is for a potential final checkpoint\n # and use the last completed step from the state.\n actual_step = (int(state.step) - 1) if step is None else int(step)\n\n # Determine if a checkpoint save should be forced, overriding the usual `config.checkpoint_period` logic.\n # This occurs if this function was called:\n # without an explicit 'step' (implying it's a checkpoint save for final step),\n # AND the 'actual_step' is a valid step,\n # AND it's not a step that would normally trigger a checkpoint save.\n force_ckpt_save = step is None and actual_step != -1 and (actual_step % config.checkpoint_period != 0)\n\n try:\n checkpoint_saved = save_checkpoint(checkpoint_manager, actual_step, state, config, data_iterator, force_ckpt_save)\n if checkpoint_saved:\n print_save_message(actual_step, config.async_checkpointing)\n except Exception as e:\n raise exceptions.StopTraining(f""Checkpointing failed. {str(e)}"") from e\n\n # Wait for any pending checkpoint save to finish during preemption or final step save\n if force_ckpt_save or checkpoint_manager.reached_preemption(actual_step):\n checkpoint_manager.wait_until_finished()\n\n # Raise exception upon preemption\n if checkpoint_manager.reached_preemption(actual_step):\n raise exceptions.StopTraining(""Job is preempted."")\n\n\ndef save_checkpoint(checkpoint_manager, step, state, config=None, data_iterator=None, force=False):\n """"""Wrapper for saving checkpoint.""""""\n if config and config.enable_checkpointing:\n if (\n force\n or (step % config.checkpoint_period == 0)\n or (config.enable_emergency_checkpoint and step % config.local_checkpoint_period == 0)\n ):\n blocking_until_ready_start = time.time()\n max_logging.log(f""Waiting for step {step} to finish before checkpoint..."")\n # We block here on the step finishing so that our checkpointing metrics\n # measure only checkpointing time, not training time.\n jax.block_until_ready(state)\n max_logging.log(\n f""Waited {time.time() - blocking_until_ready_start} seconds for step ""\n f""{step} to finish before starting checkpointing.""\n )\n\n # specify chunk_byte_size to force orbax to control maximum file size in checkpoint\n chunk_byte_size = (\n config.checkpoint_storage_target_data_file_size_bytes if config else DEFAULT_OCDBT_TARGET_DATA_FILE_SIZE\n )\n\n checkpoint_args = ocp.args.PyTreeSave(\n item=state,\n save_args=jax.tree.map(lambda _: ocp.SaveArgs(chunk_byte_size=chunk_byte_size), state),\n ocdbt_target_data_file_size=chunk_byte_size,\n )\n\n match (checkpoint_manager, config):\n case (checkpoint_manager, _) if isinstance(\n checkpoint_manager, (EmergencyCheckpointManager, EmergencyReplicatorCheckpointManager)\n ):\n replicator_error_handler(config)\n return checkpoint_manager.save(step, args=Composite(state=checkpoint_args), force=force)\n case (_, config) if config and config.dataset_type == ""grain"":\n grain_iter = grain.PyGrainCheckpointSave(data_iterator.local_iterator)\n return checkpoint_manager.save(step, args=Composite(items=checkpoint_args, iter=grain_iter), force=force)\n case _:\n return checkpoint_manager.save(step, args=Composite(items=checkpoint_args), force=force)\n",python,tab
|
| 3 |
+
2,297,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"4:00:55 PM [info] Activating crowd-code\n4:00:55 PM [info] Recording started\n4:00:55 PM [info] Initializing git provider using file system watchers...\n",Log,tab
|
| 4 |
+
3,404,"extension-output-pdoom-org.crowd-code-#1-crowd-code",150,0,"4:00:55 PM [info] Git repository found\n4:00:55 PM [info] Git provider initialized successfully\n4:00:55 PM [info] Initial git state: [object Object]\n",Log,content
|
| 5 |
+
4,8131,"MaxText/train_utils.py",0,0,"# Copyright 2023–2025 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the ""License"");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an ""AS IS"" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# pylint: disable=bare-except, consider-using-generator\n"""""" Utils that are only interesting for training in MaxText. """"""\n\nimport jax\nfrom MaxText.common_types import MODEL_MODE_TRAIN\nfrom MaxText.layers import quantizations\nfrom MaxText.layers import models\nfrom MaxText import optimizers\nfrom MaxText import checkpointing\nfrom MaxText import maxtext_utils\n\n\ndef get_transformer_model(config, mesh, quant):\n if config.model_fsdp_ag_once:\n return models.ZeroOneTransformer(config, mesh, quant=quant, model_mode=MODEL_MODE_TRAIN)\n else:\n return models.Transformer(config, mesh, quant=quant, model_mode=MODEL_MODE_TRAIN)\n\n\ndef create_model(config, mesh):\n """"""Instantiates and returns the model object, sharded across the mesh.""""""\n # Model definition\n quant = quantizations.configure_quantization(config)\n model = get_transformer_model(config, mesh, quant)\n model = quantizations.maybe_quantize_model(model, config)\n return model\n\n\ndef create_training_tools(config, model, mesh):\n """"""Creates the init_rng, optimizer, learning rate schedule, and checkpoint manager.""""""\n init_rng = jax.random.PRNGKey(config.init_weights_seed)\n learning_rate_schedule = maxtext_utils.create_learning_rate_schedule(config)\n tx = optimizers.get_optimizer(config, learning_rate_schedule)\n logger = checkpointing.setup_checkpoint_logger(config)\n if config.enable_emergency_checkpoint:\n if config.use_replicator_service:\n checkpoint_manager = checkpointing.create_orbax_emergency_replicator_checkpoint_manager(\n config.local_checkpoint_directory,\n config.local_checkpoint_period,\n mesh,\n )\n else:\n abstract_state, _, _ = maxtext_utils.get_abstract_state(model, tx, config, init_rng, mesh, is_training=True)\n checkpoint_manager = checkpointing.create_orbax_emergency_checkpoint_manager(\n config.local_checkpoint_directory,\n config.checkpoint_dir,\n mesh,\n abstract_state,\n config.local_checkpoint_period,\n config.checkpoint_period,\n logger,\n )\n else:\n # TODO(b/368121306): Remove this once zarr3 support is plumbed on the backend\n use_ocdbt = config.checkpoint_storage_use_ocdbt\n use_zarr3 = config.checkpoint_storage_use_zarr3\n if config.enable_single_controller:\n use_ocdbt, use_zarr3 = False, False\n\n checkpoint_dir = """"\n if config.enable_checkpointing:\n checkpoint_dir = config.checkpoint_dir\n checkpoint_manager = checkpointing.create_orbax_checkpoint_manager(\n checkpoint_dir,\n config.enable_checkpointing,\n config.async_checkpointing,\n config.checkpoint_period,\n config.dataset_type,\n logger,\n use_ocdbt,\n use_zarr3,\n )\n\n return init_rng, checkpoint_manager, learning_rate_schedule, tx\n\n\ndef jit_train_step(config, model, state, state_mesh_shardings, data_sharding, train_step):\n """"""Returns a JIT-compiled train step function, which is loaded from a file if specified in the config.""""""\n functional_train, in_shardings, out_shardings, static_argnums, donate_argnums = (\n maxtext_utils.get_functional_train_with_signature(train_step, data_sharding, state_mesh_shardings, model, config)\n )\n\n # Define the compilation of functional_train, either by loading the compiled version or wrapping a new one in a jit\n if config.compiled_trainstep_file != """":\n print(""Loading the compiled function..."", flush=True)\n # Need to pass train signature and state to determine i/o shapes of train_state for now.\n p_train_step = maxtext_utils.load_compiled(config, functional_train, state)\n print(""Loaded compiled function!"", flush=True)\n else:\n p_train_step = jax.jit(\n functional_train,\n in_shardings=in_shardings,\n out_shardings=out_shardings,\n static_argnums=static_argnums,\n donate_argnums=donate_argnums,\n )\n\n return p_train_step\n\n\ndef jit_eval_step(config, model, state_mesh_shardings, data_sharding, eval_step):\n """"""Returns a JIT-compiled eval step function.""""""\n functional_eval, in_shardings, out_shardings, static_argnums, donate_argnums = (\n maxtext_utils.get_functional_eval_with_signature(eval_step, data_sharding, state_mesh_shardings, model, config)\n )\n\n p_eval_step = None\n if config.compiled_trainstep_file == """":\n p_eval_step = jax.jit(\n functional_eval,\n in_shardings=in_shardings,\n out_shardings=out_shardings,\n static_argnums=static_argnums,\n donate_argnums=donate_argnums,\n )\n\n return p_eval_step\n\n\ndef jit_train_and_eval_step(\n config, model, mesh, state, state_mesh_shardings, train_step, eval_step=None, eval_data_iterator=None\n):\n """"""Returns a JIT-compiled train and eval step function.""""""\n data_sharding = maxtext_utils.get_input_data_sharding(config, mesh)\n p_train_step = jit_train_step(config, model, state, state_mesh_shardings, data_sharding, train_step)\n p_eval_step = None\n if eval_data_iterator:\n p_eval_step = jit_eval_step(config, model, state_mesh_shardings, data_sharding, eval_step)\n\n return p_train_step, p_eval_step\n",python,tab
|
| 6 |
+
5,9095,"MaxText/checkpointing.py",0,0,"",python,tab
|
| 7 |
+
6,11430,"MaxText/checkpointing.py",16130,0,"",python,selection_command
|
| 8 |
+
7,12116,"MaxText/train_utils.py",0,0,"",python,tab
|
| 9 |
+
8,12689,"MaxText/checkpointing.py",0,0,"",python,tab
|
| 10 |
+
9,78031,"MaxText/maxtext_utils.py",0,0,"# Copyright 2023–2025 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the ""License"");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an ""AS IS"" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# pylint: disable=line-too-long, disable=bare-except, consider-using-generator\n"""""" Utils that are only interesting to MaxText. """"""\n\nimport functools\nimport pickle\n\nfrom flax import linen as nn\nfrom flax.linen import partitioning as nn_partitioning\nfrom flax.training import train_state\n\nimport numpy as np\n\nfrom collections.abc import Iterable\nfrom jax.experimental import mesh_utils\nfrom jax.experimental.serialize_executable import deserialize_and_load\nfrom jax.sharding import PartitionSpec as P\n\nimport jax\nimport jax.numpy as jnp\nimport jax.tree_util as jtu\n\nimport optax\n\nimport orbax.checkpoint.experimental.emergency.checkpoint_manager as emergency_checkpoint_manager\nimport orbax.checkpoint.experimental.emergency.replicator_checkpoint_manager as emergency_replicator_checkpoint_manager\n\nfrom MaxText import checkpointing\nfrom MaxText import max_logging\nfrom MaxText import max_utils\nfrom MaxText.common_types import DecoderBlockType, MODEL_MODE_PREFILL, MODEL_MODE_AUTOREGRESSIVE\nfrom MaxText.inference.page_manager import PageState\n\nOVERWRITE_WITH_GRADIENT = ""_overwrite_with_gradient""\n\n# Multimodal constants\nNUM_IMAGES_PER_SEQUENCE = 1\nNUM_IMAGE_CHANNELS = 3\nNUM_TILES_PER_IMAGE = 1 # Fake number of tiles for llama4, init purpose\n\n\ndef get_input_data_sharding(config, mesh):\n """"""Get the input data sharding for the model""""""\n return nn.logical_to_mesh_sharding(P(*config.input_data_sharding_logical_axes), mesh, config.logical_axis_rules)\n\n\ndef get_functional_train_with_signature(train_step, data_sharding, state_mesh_shardings, model, config):\n """"""Get the shardings (both state and data) for `train_step`.""""""\n functional_train = functools.partial(train_step, model, config, state_mesh_shardings)\n functional_train.__name__ = ""train_step""\n in_shardings = (state_mesh_shardings, data_sharding, None) # State, batch, rng\n out_shardings = (state_mesh_shardings, None) # State, metrics\n static_argnums = () # We partial out the static argnums of model and config\n donate_argnums = 0 # This is the index of the state - we allow the compiler to make use of this memory.\n return functional_train, in_shardings, out_shardings, static_argnums, donate_argnums\n\n\ndef get_functional_eval_with_signature(eval_step, data_sharding, state_mesh_shardings, model, config):\n """"""Get the shardings (both state and data) for `eval_step`.""""""\n functional_eval = functools.partial(eval_step, model, config)\n functional_eval.__name__ = ""eval_step""\n in_shardings = (state_mesh_shardings, data_sharding, None) # State, batch, rng\n out_shardings = None # metrics\n static_argnums = () # We partial out the static argnums of model, config\n donate_argnums = () # state will be kept instead of being donated in eval_step\n return functional_eval, in_shardings, out_shardings, static_argnums, donate_argnums\n\n\ndef get_shaped_batch(config):\n """"""Return the shape of the batch - this is what eval_shape would return for the\n output of create_data_iterator, but eval_shape doesn't work, see b/306901078.""""""\n batch_shape = (config.global_batch_size_to_load, config.max_target_length)\n shaped_batch = {}\n shaped_batch[""inputs""] = jax.ShapeDtypeStruct(batch_shape, jnp.int32)\n shaped_batch[""inputs_position""] = jax.ShapeDtypeStruct(batch_shape, jnp.int32)\n shaped_batch[""inputs_segmentation""] = jax.ShapeDtypeStruct(batch_shape, jnp.int32)\n shaped_batch[""targets""] = jax.ShapeDtypeStruct(batch_shape, jnp.int32)\n shaped_batch[""targets_position""] = jax.ShapeDtypeStruct(batch_shape, jnp.int32)\n shaped_batch[""targets_segmentation""] = jax.ShapeDtypeStruct(batch_shape, jnp.int32)\n if config.use_multimodal:\n image_shape = get_dummy_image_shape_for_init(config)\n shaped_batch[""images""] = jax.ShapeDtypeStruct(image_shape, jnp.int32)\n return shaped_batch\n\n\ndef get_dummy_image_shape_for_init(config):\n """"""Return the shape of the dummy image for specific model's initialization.""""""\n image_shape = ()\n if config.model_name.startswith(""gemma3""):\n image_shape = (\n config.micro_batch_size_to_train_on,\n NUM_IMAGES_PER_SEQUENCE,\n config.image_size_for_vit,\n config.image_size_for_vit,\n NUM_IMAGE_CHANNELS,\n )\n elif config.model_name.startswith(""llama4""):\n image_shape = (\n config.micro_batch_size_to_train_on,\n NUM_TILES_PER_IMAGE,\n NUM_IMAGE_CHANNELS,\n config.tile_size_for_vit,\n config.tile_size_for_vit,\n )\n return image_shape\n\n\ndef load_compiled(config, partial_train, state):\n """"""# Loading a serialized compiled train step function.""""""\n\n # Currently partial_train and state are needed to reconstruct\n # input/output shapes to construct the in_trees and out_trees for load API\n # Parker is working on a serializing these\n def load_serialized_compiled(save_name):\n with open(save_name, ""rb"") as f:\n serialized_compiled = pickle.load(f)\n return serialized_compiled\n\n def get_train_input_output_trees(func, input_args, input_kwargs):\n _, in_tree_recreated = jax.tree_util.tree_flatten((input_args, input_kwargs))\n out_shaped = jax.eval_shape(func, *input_args, **input_kwargs)\n _, out_tree_recreated = jax.tree_util.tree_flatten(out_shaped)\n return in_tree_recreated, out_tree_recreated\n\n serialized_compiled = load_serialized_compiled(config.compiled_trainstep_file)\n shaped_batch = get_shaped_batch(config)\n example_rng = jax.random.PRNGKey(0)\n shaped_input_args = (state, shaped_batch, example_rng)\n shaped_input_kwargs = {}\n in_tree, out_tree = get_train_input_output_trees(partial_train, shaped_input_args, shaped_input_kwargs)\n p_train_step = deserialize_and_load(serialized_compiled, in_tree, out_tree)\n return p_train_step\n\n\ndef calculate_tokens_training_per_device(config):\n """"""Calculate training Tokens per device""""""\n return config.max_target_length * config.per_device_batch_size * config.gradient_accumulation_steps\n\n\ndef calculate_gemma2_tflops_training_per_device(config, total_ffn_flops, qkv_flops, projection_flops, embedding_flops):\n """"""\n Calculate training TFLOP for Gemma2 as in Gemma2 we combine [local_attention, global_attention] into one decoder\n layer and we use sliding window attention in local_attention\n """"""\n noncausal_attention_flops = (\n # global attention\n 4 * config.per_device_batch_size * config.max_target_length**2 * config.num_query_heads * config.head_dim\n +\n # local attention\n 4\n * config.per_device_batch_size\n * config.max_target_length\n * min(config.sliding_window_size, config.max_target_length)\n * config.num_query_heads\n * config.head_dim\n )\n causal_attention_flops = noncausal_attention_flops / 2\n attention_tflops = causal_attention_flops * config.num_decoder_layers * 3 / 10**12\n\n # multiply num_decoder_layers by 2 because we combine [local_attention, global_attention] into one decoder layer\n learnable_weight_tflops = (\n ((total_ffn_flops + qkv_flops + projection_flops) * config.num_decoder_layers * 2 + embedding_flops) * 3 / 10**12\n )\n\n return attention_tflops, learnable_weight_tflops\n\n\ndef calculate_gemma3_tflops_training_per_device(config, total_ffn_flops, qkv_flops, projection_flops, embedding_flops):\n """"""\n Calculate training TFLOPs for Gemma3, which has an alternating pattern of\n 5 local attention layers and 1 global attention layer.\n """"""\n num_layers = config.num_decoder_layers\n\n num_global_layers = num_layers // 6\n num_local_layers = num_layers - num_global_layers\n\n # FLOPs for a single global attention layer (full attention)\n # Formula: 4 * batch_size * seq_len^2 * num_heads * head_dim\n global_attention_flops_per_layer = (\n 4 * config.per_device_batch_size * config.max_target_length**2 * config.num_query_heads * config.head_dim\n )\n\n # FLOPs for a single local attention layer (sliding window)\n # Formula: 4 * batch_size * seq_len * window_size * num_heads * head_dim\n local_attention_flops_per_layer = (\n 4\n * config.per_device_batch_size\n * config.max_target_length\n * min(config.sliding_window_size, config.max_target_length)\n * config.num_query_heads\n * config.head_dim\n )\n\n # Total attention FLOPs = (num_global_layers * FLOPs_per_global) + (num_local_layers * FLOPs_per_local)\n noncausal_attention_flops = (\n num_global_layers * global_attention_flops_per_layer + num_local_layers * local_attention_flops_per_layer\n )\n causal_attention_flops = noncausal_attention_flops / 2\n\n # Convert to TFLOPs and multiply by 3 for fwd/bwd pass\n attention_tflops = causal_attention_flops * 3 / 10**12\n\n # Learnable weights (FFN, QKV, Projections) are present in every layer.\n learnable_weight_tflops = ((total_ffn_flops + qkv_flops + projection_flops) * num_layers + embedding_flops) * 3 / 10**12\n\n return attention_tflops, learnable_weight_tflops\n\n\ndef _calculate_chunked_attention_flops_per_layer(config, seq_len, chunk_size):\n """"""Calculates the non-causal FLOPs for a single layer of chunked attention.""""""\n num_chunks = seq_len // chunk_size\n rem_chunk_size = seq_len % chunk_size\n # The complexity of chunked attention is the sum of squares of chunk lengths.\n chunked_complexity = (num_chunks * chunk_size**2) + (rem_chunk_size**2)\n # The formula for non-causal attention FLOPs is 4 * B * complexity * H * D,\n # where B=batch_size, H=num_heads, D=head_dim.\n return 4 * config.per_device_batch_size * chunked_complexity * config.num_query_heads * config.head_dim\n\n\ndef calculate_llama4_attention_tflops(config):\n """"""\n Calculates attention-only training TFLOPs for Llama4's specific architecture,\n which has an alternating pattern of global and chunked attention layers.\n """"""\n num_layers = config.num_decoder_layers\n seq_len = config.max_target_length\n chunk_size = config.chunk_attn_window_size\n\n # Determine number of global vs. chunked layers based on the NoPE interval.\n # A ""NoPE"" layer uses global attention.\n num_global_layers = num_layers // config.nope_layer_interval\n num_chunked_layers = num_layers - num_global_layers\n\n # FLOPs for a single global attention layer (full attention, non-causal)\n global_attention_flops_per_layer = (\n 4 * config.per_device_batch_size * seq_len**2 * config.num_query_heads * config.head_dim\n )\n\n # FLOPs for a single chunked attention layer (non-causal)\n chunked_attention_flops_per_layer = _calculate_chunked_attention_flops_per_layer(config, seq_len, chunk_size)\n\n # Total non-causal attention FLOPs is the sum of all global and all chunked layers\n noncausal_attention_flops = (num_global_layers * global_attention_flops_per_layer) + (\n num_chunked_layers * chunked_attention_flops_per_layer\n )\n\n # Apply causal mask and convert to TFLOPs (multiply by 3 for fwd/bwd pass)\n causal_attention_flops = noncausal_attention_flops / 2\n attention_tflops = causal_attention_flops * 3 / 10**12\n\n return attention_tflops\n\n\ndef calculate_mla_tflops_per_device(config):\n """"""Calculate Multi-Head Latent Attention TFLOP""""""\n batch_len = config.per_device_batch_size * config.max_target_length\n qk_head_dim_sum = config.qk_nope_head_dim + config.qk_rope_head_dim\n # calculate mla query projection\n if config.q_lora_rank == 0:\n q_flops = 2 * batch_len * config.emb_dim * config.num_query_heads * qk_head_dim_sum\n else:\n # calculate query down and up flops\n q_flops = (\n 2\n * batch_len\n * (config.emb_dim * config.q_lora_rank + config.q_lora_rank * config.num_query_heads * qk_head_dim_sum)\n )\n # calculate mla kv projection with down and up flops\n kv_flops = (\n 2\n * batch_len\n * (\n config.emb_dim * (config.kv_lora_rank + config.qk_rope_head_dim)\n + config.kv_lora_rank * config.num_query_heads * (config.qk_nope_head_dim + config.v_head_dim)\n )\n )\n qkv_flops = q_flops + kv_flops\n\n attention_flops = (\n 2 * batch_len * config.max_target_length * config.num_query_heads * (qk_head_dim_sum + config.v_head_dim)\n )\n projection_flops = 2 * batch_len * config.emb_dim * config.num_query_heads * config.v_head_dim\n return qkv_flops, attention_flops, projection_flops\n\n\ndef calculate_ffn_mamtul_tflops_per_device(config, mlp_dim):\n """"""Helper function to calculate matmul TFLOP in ffn based on MLP dimension.\n\n Applies to:\n - Dense FFN layers (mlp_dim = config.mlp_dim).\n - MoE FFN layers (mlp_dim = config.moe_mlp_dim),\n need to scale by shared_experts or num_experts_per_tok.\n """"""\n ffn1_flops = (\n 2 * config.per_device_batch_size * config.max_target_length * mlp_dim * config.emb_dim * len(config.mlp_activations)\n )\n ffn2_flops = 2 * config.per_device_batch_size * config.max_target_length * mlp_dim * config.emb_dim\n return ffn1_flops + ffn2_flops\n\n\ndef calculate_routed_and_shared_ffn_tflops_per_device(config):\n """"""Helper function to calculate DeepSeek-style ffn TFLOP""""""\n gate_flops = 2 * config.per_device_batch_size * config.max_target_length * config.emb_dim * config.num_experts\n # Due to the mixed decoder layers, the flops is multiplied by num of layers for both dense and moe\n num_dense_layers, num_moe_layers = get_dense_moe_layers(config)\n dense_ffn_flops = calculate_ffn_mamtul_tflops_per_device(config, config.mlp_dim) * num_dense_layers\n shared_experts_flops = calculate_ffn_mamtul_tflops_per_device(config, config.moe_mlp_dim) * config.shared_experts\n routed_experts_flops = calculate_ffn_mamtul_tflops_per_device(config, config.moe_mlp_dim) * config.num_experts_per_tok\n moe_ffn_flops = (gate_flops + shared_experts_flops + routed_experts_flops) * num_moe_layers\n total_ffn_flops = dense_ffn_flops + moe_ffn_flops\n return total_ffn_flops\n\n\ndef get_dense_moe_layers(config):\n """"""Helper function to calculate number of dense and moe layers""""""\n if config.decoder_block == DecoderBlockType.DEEPSEEK:\n num_dense_layers = config.first_num_dense_layers\n num_moe_layers = config.num_decoder_layers - config.first_num_dense_layers\n return num_dense_layers, num_moe_layers\n elif config.decoder_block == DecoderBlockType.LLAMA4:\n num_moe_layers = config.num_decoder_layers // config.interleave_moe_layer_step\n num_dense_layers = config.num_decoder_layers - num_moe_layers\n else:\n raise ValueError(""Currently we only support DeepSeek and Llama4 calculation."")\n\n return num_dense_layers, num_moe_layers\n\n\ndef calculate_gemma3_vision_layers_tflops_per_device(config):\n """"""\n Estimate TFLOPs for Gemma3 vision encoder (ViT-style).\n Returns:\n total_tflops: Total TFLOPs (counts for fwd + bwd + optimizer)\n learnable_weight_tflops: TFLOPs from learnable weights (patch embedding, qkv, MLP, projections)\n attention_tflops: TFLOPs from attention multiplications\n """"""\n # Config values\n B = config.per_device_batch_size\n C = config.num_channels_for_vit\n H = W = config.image_size_for_vit # Gemma3 default 896\n embed_dim = config.emb_dim # text embedding dim after projection\n # Values below are hardcoded in Gemma3VisionEncoderLayer\n patch_size = 14\n hidden_dim = 1152\n intermediate_dim = 4304\n num_layers = 27\n vision_exit_pooling_window = 4\n\n # 1. Patch embedding (Conv2D)\n num_patches_h = H // patch_size\n num_patches_w = W // patch_size\n seq_len = num_patches_h * num_patches_w # 64*64=4096\n patch_embed_flops = 2 * B * seq_len * (C * patch_size * patch_size) * hidden_dim\n\n # 2. gemma3.Encoder: num_layers * gemma3.Encoder1DBlock\n qkv_flops_per_layer = 3 * (2 * B * seq_len * hidden_dim * hidden_dim)\n attn_flops_per_layer = 4 * B * seq_len * seq_len * hidden_dim\n projection_flops_per_layer = 2 * B * seq_len * hidden_dim * hidden_dim # projection after attention multiplication\n mlp_flops_per_layer = 2 * (2 * B * seq_len * hidden_dim * intermediate_dim) # two fc layers\n total_attn_flops = attn_flops_per_layer * num_layers\n encoder_flops = (+qkv_flops_per_layer + projection_flops_per_layer + mlp_flops_per_layer) * num_layers\n\n # 4. VisionEmbedder\n seq_len_after_pooling = (num_patches_h // vision_exit_pooling_window) * (num_patches_w // vision_exit_pooling_window)\n vision_embedder_flops = 2 * B * seq_len_after_pooling * hidden_dim * embed_dim # One linear projection\n\n # Learnable weights summation\n learnable_weight_flops = patch_embed_flops + encoder_flops + vision_embedder_flops\n\n if config.freeze_vision_encoder_params:\n learnable_weight_flops += 2 * vision_embedder_flops # only projector is learnable, add fwd+optimizer\n else:\n learnable_weight_flops *= 3 # multiply by 3 for fwd + bwd + optimizer\n\n # Convert to TFLOPs\n learnable_weight_tflops = learnable_weight_flops / 1e12\n total_attn_tflops = total_attn_flops / 1e12\n total_tflops = learnable_weight_tflops + total_attn_tflops\n\n return total_tflops, learnable_weight_tflops, total_attn_tflops\n\n\ndef calculate_llama4_vision_layers_tflops_per_device(config):\n """"""\n Estimate TFLOPs for Llama4 vision encoder (ViT-style).\n Returns:\n total_tflops: Total TFLOPs (counts for fwd + bwd + optimizer)\n learnable_weight_tflops: TFLOPs from learnable weights (patch embedding, qkv, MLP, projections)\n attention_tflops: TFLOPs from attention multiplications\n """"""\n # Config values\n B = config.per_device_batch_size\n C = config.num_channels_for_vit\n H = W = config.tile_size_for_vit\n patch_size = config.patch_size_for_vit\n hidden_dim = config.hidden_size_for_vit\n intermediate_dim = config.intermediate_size_for_vit\n num_layers = config.num_hidden_layers_for_vit\n pixel_shuffle_fc1_out_dim = config.projector_input_dim_for_vit # 4096\n pixel_shuffle_fc2_out_dim = config.projector_output_dim_for_vit # 4096\n base_emb_dim = config.base_emb_dim\n pixel_shuffle_ratio = config.pixel_shuffle_ratio_for_vit # 0.5\n num_patches = (H // patch_size) * (W // patch_size) # 24*24 = 576\n pixel_shuffle_tokens = num_patches * pixel_shuffle_ratio**2 # 144\n\n # 1. Llama4UnfoldConvolution (flops by linear projection)\n # lax.conv_general_dilated_patches extracts patches through reshaping/indexing without flops\n # Each patch: C * patch_size * patch_size -> hidden_dim\n patch_embed_flops = 2 * B * num_patches * (C * patch_size * patch_size) * hidden_dim\n\n # 2. Llama4VisionEncoder: num_layers * (qkv + att_projection + mlp)\n seq_len = num_patches + 1 # +1 for class token, so 577\n qkv_flops_per_layer = 3 * (2 * B * seq_len * hidden_dim * hidden_dim) # Q, K, V projections\n attn_flops_per_layer = 4 * B * seq_len * seq_len * hidden_dim # Attention scores and weighted sum\n projection_flops_per_layer = 2 * B * seq_len * hidden_dim * hidden_dim # projection after attention multiplication\n mlp_flops_per_layer = 2 * (2 * B * seq_len * hidden_dim * intermediate_dim) # two fc layers\n total_attn_flops = attn_flops_per_layer * num_layers\n vision_encoder_flops = (+qkv_flops_per_layer + projection_flops_per_layer + mlp_flops_per_layer) * num_layers\n\n # 3. Llama4VisionPixelShuffleMLP\n # (B, 144, 5632) -> (B, 144, 4096) -> (B, 144, 4096)\n pixel_shuffle_fc1_flops = 2 * B * pixel_shuffle_tokens * intermediate_dim * pixel_shuffle_fc1_out_dim\n pixel_shuffle_fc2_flops = 2 * B * pixel_shuffle_tokens * pixel_shuffle_fc1_out_dim * pixel_shuffle_fc2_out_dim\n pixel_shuffle_total_flops = pixel_shuffle_fc1_flops + pixel_shuffle_fc2_flops\n\n # 4. Llama4MultiModalProjector: (B, 144, 5120) x (5120, base_emb_dim)\n projector_flops = 2 * B * pixel_shuffle_tokens * pixel_shuffle_fc1_out_dim * base_emb_dim\n\n # Learnable weights: all matmuls above\n learnable_weight_flops = patch_embed_flops + vision_encoder_flops + pixel_shuffle_total_flops + projector_flops\n\n if config.freeze_vision_encoder_params:\n learnable_weight_flops += 2 * projector_flops # only projector is learnable, add fwd+optimizer\n else:\n learnable_weight_flops *= 3 # multiply by 3 for fwd + bwd + optimizer\n\n # Convert to TFLOPs\n learnable_weight_tflops = learnable_weight_flops / 1e12\n total_attn_tflops = total_attn_flops / 1e12\n total_tflops = learnable_weight_tflops + total_attn_tflops\n\n return total_tflops, learnable_weight_tflops, total_attn_tflops\n\n\ndef calculate_vision_encoder_tflops(config):\n """"""Calculate vision encoder TFLOPs per prefill step per device.""""""\n if config.model_name.startswith(""gemma3""):\n mm_total_tflops, mm_learnable_weight_tflops, mm_attention_tflops = calculate_gemma3_vision_layers_tflops_per_device(\n config\n )\n elif config.model_name.startswith(""llama4""):\n mm_total_tflops, mm_learnable_weight_tflops, mm_attention_tflops = calculate_llama4_vision_layers_tflops_per_device(\n config\n )\n else:\n max_logging.log(\n f""Vision encoder TFLOPs calculation not implemented for model {config.model_name}, counting as 0 for now.""\n )\n mm_total_tflops = mm_learnable_weight_tflops = mm_attention_tflops = 0\n\n return mm_total_tflops, mm_learnable_weight_tflops, mm_attention_tflops\n\n\ndef calculate_tflops_training_per_device(config, log=True):\n """"""Calculate training TFLOP""""""\n # MLP flops\n if config.num_experts > 1:\n # calculation based on dropless implementation\n if config.decoder_block in (DecoderBlockType.DEEPSEEK, DecoderBlockType.LLAMA4):\n total_ffn_flops = calculate_routed_and_shared_ffn_tflops_per_device(config)\n else:\n gate_flops = 2 * config.per_device_batch_size * config.max_target_length * config.emb_dim * config.num_experts\n total_ffn_flops = (\n gate_flops + calculate_ffn_mamtul_tflops_per_device(config, config.mlp_dim) * config.num_experts_per_tok\n )\n else:\n total_ffn_flops = calculate_ffn_mamtul_tflops_per_device(config, config.mlp_dim)\n\n # Attention flops\n if config.attention_type == ""mla"":\n qkv_flops, noncausal_attention_flops, projection_flops = calculate_mla_tflops_per_device(config)\n else:\n qkv_flops = (\n 2\n * config.per_device_batch_size\n * config.max_target_length\n * config.emb_dim\n * (config.num_query_heads + 2 * config.num_kv_heads)\n * config.head_dim\n )\n noncausal_attention_flops = (\n 4 * config.per_device_batch_size * config.max_target_length**2 * config.num_query_heads * config.head_dim\n )\n projection_flops = (\n 2\n * config.per_device_batch_size\n * config.max_target_length\n * config.emb_dim\n * config.num_query_heads\n * config.head_dim\n )\n\n # Divide attention flops by 2 due to causal mask\n # References:\n # NVIDIA/Megatron-LM (2025 March): https://github.com/NVIDIA/Megatron-LM/blob/250b79415dcc4b660521273c87f15334c804eeae/megatron/training/training.py#L361-L362\n # NVIDIA/NeMo (2025 April): https://github.com/NVIDIA/NeMo/blob/ba4d6d116463de512ff0cfc14641aa6cf4577a42/nemo/utils/flops_formulas.py#L259-L272\n causal_attention_flops = noncausal_attention_flops / 2\n\n # Embedding flops\n embedding_flops = 2 * config.per_device_batch_size * config.max_target_length * config.emb_dim * config.vocab_size\n\n # Combine flops with number of decoder layers\n if config.decoder_block == DecoderBlockType.GEMMA2:\n attention_tflops, learnable_weight_tflops = calculate_gemma2_tflops_training_per_device(\n config, total_ffn_flops, qkv_flops, projection_flops, embedding_flops\n )\n elif config.decoder_block == DecoderBlockType.GEMMA3:\n attention_tflops, learnable_weight_tflops = calculate_gemma3_tflops_training_per_device(\n config, total_ffn_flops, qkv_flops, projection_flops, embedding_flops\n )\n elif config.decoder_block == DecoderBlockType.LLAMA4:\n # Use the new helper to calculate attention TFLOPs correctly.\n attention_tflops = calculate_llama4_attention_tflops(config)\n # The learnable weight calculation remains the same as it correctly handles Llama4's MoE structure.\n learnable_weight_tflops = (\n (total_ffn_flops + (qkv_flops + projection_flops) * config.num_decoder_layers + embedding_flops) * 3 / 10**12\n )\n elif config.decoder_block == DecoderBlockType.DEEPSEEK:\n learnable_weight_tflops = (\n (total_ffn_flops + (qkv_flops + projection_flops) * config.num_decoder_layers + embedding_flops) * 3 / 10**12\n )\n attention_tflops = causal_attention_flops * config.num_decoder_layers * 3 / 10**12\n else:\n # multiply by 3 for both feed forward and back propagation flops\n learnable_weight_tflops = (\n ((total_ffn_flops + qkv_flops + projection_flops) * config.num_decoder_layers + embedding_flops) * 3 / 10**12\n )\n attention_tflops = causal_attention_flops * config.num_decoder_layers * 3 / 10**12\n\n learnable_weight_tflops = learnable_weight_tflops * config.gradient_accumulation_steps\n attention_tflops = attention_tflops * config.gradient_accumulation_steps\n\n # DPO includes one additional forward pass per gradient accumulation step\n if config.use_dpo:\n reference_model_tflops = learnable_weight_tflops / 3 # additional forward pass\n reference_model_attention_tflops = attention_tflops / 3\n attention_tflops = attention_tflops + reference_model_attention_tflops\n else:\n reference_model_tflops = 0\n\n total_tflops = learnable_weight_tflops + attention_tflops + reference_model_tflops\n\n if config.use_multimodal:\n # Add vision layers TFLOPs for multimodal models\n mm_total_tflops, mm_learnable_weight_tflops, mm_attention_tflops = calculate_vision_encoder_tflops(config)\n if log:\n print(\n f""{config.model_name} vision layers per train step:\n"",\n f""Total TFLOPs: {mm_total_tflops:.2f} \n"",\n f""split as {100 * mm_learnable_weight_tflops/mm_total_tflops:.2f}% learnable weight flops"",\n f""and {100 * mm_attention_tflops/mm_total_tflops:.2f}% attention flops;\n"",\n f""learnable weight {mm_learnable_weight_tflops:.2f} TFLOPs, attention {mm_attention_tflops:.2f} TFLOPs"",\n )\n total_tflops += mm_total_tflops\n learnable_weight_tflops += mm_learnable_weight_tflops\n attention_tflops += mm_attention_tflops\n\n if log:\n print(\n ""Per train step:\n"",\n f""Total TFLOPs: {total_tflops:.2f} \n"",\n f""split as {100 * learnable_weight_tflops/total_tflops:.2f}% learnable weight flops"",\n f""and {100 * attention_tflops/total_tflops:.2f}% attention flops"",\n )\n return total_tflops, learnable_weight_tflops, attention_tflops\n\n\n# https://arxiv.org/pdf/2204.02311.pdf Appendix B\ndef calculate_prefill_tflops_per_device(num_model_parameters, prefill_length, config, log=True):\n """"""Calculate training TFLOP""""""\n learnable_weight_tflops = 2 * num_model_parameters * prefill_length / jax.device_count() / 1e12\n noncausal_attention_flops = (\n 4\n * config.num_query_heads\n * config.num_decoder_layers\n * config.head_dim\n * prefill_length**2\n / jax.device_count()\n / 1e12\n )\n causal_attention_tflops = noncausal_attention_flops / 2 # due to causality in attention\n total_tflops = learnable_weight_tflops + causal_attention_tflops\n\n if log:\n print(\n ""Per prefill step per device: \n"",\n f""\tTotal TFLOPs: {total_tflops:.2f} \n"",\n f""\t\tLearnable weight TFLOPs: {learnable_weight_tflops:.2f} "",\n f""({100 * learnable_weight_tflops/total_tflops:.2f})% of Total\n"",\n f""\t\tCausal attention TFLOPs: {causal_attention_tflops:.2f} "",\n f""({100 * causal_attention_tflops/total_tflops:.2f})% of Total"",\n )\n return total_tflops, learnable_weight_tflops, causal_attention_tflops\n\n\ndef get_mesh_axes_used_by_tensor_spec(tensor_sharding_spec):\n """"""\n Extracts the set of mesh axis names that a tensor's PartitionSpec uses.\n\n This function inspects a tensor's sharding specification (PartitionSpec) and\n identifies which mesh axes are actively used for sharding. If a tensor is not\n sharded (i.e., fully replicated), the resulting set will be empty.\n\n Args:\n tensor_sharding_spec: The PartitionSpec of a tensor, which defines how it's partitioned across the mesh.\n It can be None or contain strings and iterables representing the mesh axes.\n all_mesh_axis_names: A collection of all available mesh axis names in the current device mesh.\n\n Returns:\n A set of strings, where each string is a mesh axis name used by the\n tensor's sharding spec. Returns an empty set for unsharded tensors.\n """"""\n # Flatten the sharding spec, as it can contain nested iterables (e.g., ('data', 'mdl')).\n tensor_sharding_spec = sum(\n [\n [axis] if isinstance(axis, str) else list(axis) if isinstance(axis, Iterable) else []\n for axis in tensor_sharding_spec\n ],\n [],\n )\n return tensor_sharding_spec\n\n\ndef _get_nontrival_mesh_axes(mesh):\n """"""\n Returns mesh axes from config that are valid and have more than one shard.\n\n This function identifies which of the predefined potential sharding axes are\n actually present in the current device mesh and are configured with a size\n greater than one (i.e., are actually sharded).\n\n Args:\n mesh: The device mesh object, which contains information about the mesh topology, including axis names and their sizes.\n\n Returns:\n A set of strings, where each string is a mesh axis name that is both\n pre-configured as a target for sharding and has more than one shard in the mesh.\n """"""\n\n target_sharding_axes_config = [\n ""fsdp"",\n ""fsdp_transpose"",\n ""sequence"",\n ""context"",\n ""context_autoregressive"",\n ""tensor"",\n ""tensor_transpose"",\n ""tensor_sequence"",\n ""stage"",\n ""expert"",\n ]\n\n # Filter the target axes to find those that exist in the current mesh\n # and have a size greater than 1, meaning they are actually used for sharding.\n return {axis for axis in target_sharding_axes_config if axis in mesh.axis_names and mesh.shape[axis] > 1}\n\n\ndef _analyze_sharding(params, mesh, valid_target_mesh_axes):\n """"""\n Analyzes parameters to find which are unsharded on any valid mesh axis.\n\n This function iterates through all parameters in a model, checking their\n sharding specifications. It identifies parameters that are not sharded along any\n of the provided valid target axes (i.e., they are fully replicated across these axes).\n\n Args:\n params: A PyTree of model parameters.\n mesh: The device mesh object.\n valid_target_mesh_axes: A set of mesh axis names that are considered valid targets for sharding.\n\n Returns:\n A tuple containing:\n - unsharded_params_total_size (int): The total size (number of elements) of all parameters found to be\n unsharded on the target axes.\n - problematic_tensors_details (list): A list of dictionaries, where each\n dictionary contains details about a tensor that is not sharded on any of the target axes.\n """"""\n unsharded_params_total_size = 0 # Initialize a counter for the size of unsharded parameters.\n problematic_tensors_details = [] # Initialize a list to store details of problematic tensors.\n\n # Get a flattened list of all parameters (leaves) in the PyTree, along with their paths.\n all_params_leaves = jtu.tree_leaves_with_path(params)\n\n for path, p_leaf in all_params_leaves: # Iterate over each parameter leaf\n param_name_str = jtu.keystr(path) # Convert the tree path to a readable string\n\n # Check that sharding and spec exist and are valid\n sharding = getattr(p_leaf, ""sharding"", None)\n spec = getattr(sharding, ""spec"", None)\n assert sharding is not None and spec is not None and isinstance(spec, P), (\n f""Parameter '{param_name_str}' is missing a valid '.sharding.spec'.""\n ""Expected 'p_leaf.sharding.spec' to be a non-null 'partitionspec'.""\n )\n\n current_sharding_spec = p_leaf.sharding.spec # Extract the current tensor's sharding spec\n # Identify axes used for sharding\n mesh_axes_used = get_mesh_axes_used_by_tensor_spec(current_sharding_spec)\n # Check if the parameter is sharded on all the valid target axes.\n is_sharded_on_all_target_axis = all(axis in mesh_axes_used for axis in valid_target_mesh_axes)\n\n # If the parameter is not sharded on all of the target axes, it's considered ""problematic.""\n if not is_sharded_on_all_target_axis:\n unsharded_params_total_size += p_leaf.size # Add to total unsharded parameter size\n unsharded_axes = set(valid_target_mesh_axes) - set(mesh_axes_used)\n # Add detailed info to list of problematic tensors\n problematic_tensors_details.append(\n {\n ""name"": param_name_str, # Tensor name\n ""size"": p_leaf.size, # tensor size\n ""shape"": p_leaf.shape, # tensor shape\n ""spec"": str(current_sharding_spec), # Tensor sharding spec as string\n ""available_axes"": sorted(list(valid_target_mesh_axes)), # Axes that could be used for sharding\n ""unsharded_axes"": sorted(list(unsharded_axes)), # Unsharded axes\n }\n )\n # Return the total size of unsharded parameters and the list of problematic tensors.\n return unsharded_params_total_size, problematic_tensors_details # Return results\n\n\ndef _raise_if_unsharded_exceeds_tolerance(unsharded_size, total_size, tolerance, problematic_tensors_details):\n """"""\n Raises an AssertionError if the percentage of unsharded parameters exceeds the given tolerance.\n\n This function calculates the proportion of model parameters that are unsharded\n and compares it against a specified tolerance. If the tolerance is exceeded,\n it constructs and raises a detailed error message.\n\n Args:\n unsharded_size: The total size of parameters not sharded on target axes.\n total_size: The total size of all parameters in the model.\n tolerance: A float (e.g., 0.05 for 5%) representing the maximum allowed percentage of unsharded parameters.\n problematic_tensors_details: A list of details about the unsharded tensors,\n used to generate an informative error message.\n\n Raises:\n AssertionError: If the percentage of unsharded parameters is greater than the tolerance.\n """"""\n if total_size <= 0:\n raise ValueError(""Total size must be greater than zero."")\n\n # Calculate the percentage of unsharded parameters.\n unsharded_param_perc = unsharded_size / total_size\n\n # If the percentage is over the tolerance, prepare and raise an error.\n if unsharded_param_perc > tolerance:\n # Sort the problematic tensors by size to show the largest ones first.\n problematic_tensors_details.sort(key=lambda x: x[""size""], reverse=True)\n\n # Begin constructing the error message.\n error_msg_lines = [\n f""Unsharded parameter percentage ({unsharded_param_perc:.2%})"" f""exceeds tolerance ({tolerance:.2%}).""\n ]\n # Add a header explaining the issue.\n error_msg_lines.append(\n ""The following large tensors are replicated (unsharded) but could be sharded on at ""\n ""least one of the available axes:""\n )\n # Add details for the top 5 largest problematic tensors.\n for detail in problematic_tensors_details[:5]: # Show top 5 largest problematic tensors\n error_msg_lines.append(\n f"" - Name: {detail['name']}(Size: {detail['size']}, Shape: {detail['spec']}, Spec: {detail['spec']}) ""\n f"" is unsharded on axis: {detail['unsharded_axes']}""\n f"" could be sharded on: {detail['available_axes']}""\n )\n\n # Raise the assertion error with the combined, formatted message.\n raise AssertionError(""\n"".join(error_msg_lines))\n\n\ndef assert_params_sufficiently_sharded(params, mesh, tolerance):\n """"""\n Asserts that the total size of replicated parameters is within a given tolerance.\n\n This is the main function that orchestrates the sharding analysis. It determines\n the total number of parameters, identifies valid sharding axes, analyzes the\n sharding of all parameters, and then raises an error if the amount of\n unsharded parameters exceeds the specified tolerance.\n\n Args:\n params: A PyTree of model parameters.\n mesh: The device mesh object.\n tolerance: A float representing the maximum allowed percentage of unsharded parameters.\n """"""\n # Calculate the total size of all parameters in the model.\n total_num_params = max_utils.calculate_bytes_from_pytree(params)\n\n # Get the set of nontrival mesh axes that can be used for sharding.\n valid_target_mesh_axes = _get_nontrival_mesh_axes(mesh)\n # If there are no valid axes to shard along, there's nothing to check, so we can exit.\n if not valid_target_mesh_axes:\n return # Exit early\n\n # Analyze the parameters to find the total size of unsharded parameters\n # and get details on which tensors are problematic.\n unsharded_params_total_size, problematic_tensors_details = _analyze_sharding(params, mesh, valid_target_mesh_axes)\n\n # Check if the amount of unsharded parameters is within the tolerance and\n # raise an exception if it is not.\n _raise_if_unsharded_exceeds_tolerance(\n unsharded_params_total_size, total_num_params, tolerance, problematic_tensors_details\n )\n\n\ndef apply_gradient_clipping(raw_grads, state, clipping_threshold):\n """"""Applies gradient clipping to raw gradients, with special handing for FLAX fp8 stats.\n\n Args:\n raw_grads: A pytree of raw gradients.\n state: The current optimizer state.\n clipping_threshold: The gradient clipping threshold.\n\n Returns:\n A pytree of clipped gradients.\n """"""\n gradient_clip_transformation = optax.clip_by_global_norm(clipping_threshold)\n if OVERWRITE_WITH_GRADIENT in raw_grads:\n # Scales + Amax History for Delayed Tensor Scaling SHOULD NOT be clipped or affect clipping\n fp8_stats = raw_grads.pop(OVERWRITE_WITH_GRADIENT)\n grads, _ = gradient_clip_transformation.update(raw_grads, state, None)\n grads[OVERWRITE_WITH_GRADIENT] = fp8_stats # pytype: disable=unsupported-operands\n raw_grads[OVERWRITE_WITH_GRADIENT] = fp8_stats # pytype: disable=unsupported-operands\n else:\n grads, _ = gradient_clip_transformation.update(raw_grads, state, None)\n\n return grads\n\n\ndef get_nested_value(dictionary, nested_key, default=None):\n """"""\n Retrieves a value from a nested key in a dictionary.\n\n Args:\n dictionary: The dictionary to search in.\n nested_key: A tuple representing the nested key, e.g., ('level1', 'level2', 'key').\n default: The value to return if the nested key is not found.\n\n Returns:\n The value associated with the nested key, or the default value if not found.\n """"""\n current_level = dictionary\n\n for key in nested_key:\n if not isinstance(current_level, dict) or key not in current_level:\n return default\n current_level = current_level[key]\n return current_level\n\n\ndef init_decode_state(apply_fn, params) -> train_state.TrainState:\n """"""Init train state with null opt state for decode.""""""\n state = train_state.TrainState(step=0, apply_fn=apply_fn, params=params, tx=None, opt_state={}) # type: ignore\n return state\n\n\ndef init_training_state(apply_fn, params, tx):\n """"""Init train state with null opt state for decode.""""""\n state = train_state.TrainState.create(apply_fn=apply_fn, params=params, tx=tx)\n return state\n\n\ndef init_initial_state(model, tx, config, is_training, key):\n """"""\n We pass in ""static"" objects like model, tx, config as JAX compares them by\n object hash, and instantiating them inside causes pjit top-level annotations\n to fail to match as pytree prefixes if we re-instantiate.\n\n Args: model, tx, config, is_training, key\n """"""\n input_shape = (config.micro_batch_size_to_train_on, config.max_target_length)\n image_shape = get_dummy_image_shape_for_init(config)\n model_vars = model.init(\n {""params"": key, ""dropout"": key, ""aqt"": key},\n np.ones(input_shape, dtype=jnp.int32),\n np.ones(input_shape, dtype=jnp.int32),\n encoder_images=np.ones(image_shape, dtype=jnp.int32) if config.use_multimodal else None,\n )\n if is_training:\n return init_training_state(model.apply, model_vars, tx)\n return init_decode_state(model.apply, model_vars)\n\n\ndef setup_decode_state(model, config, rng, mesh, checkpoint_manager):\n """"""Setup decode state by loading params from a checkpoint.\n Args:\n model: the flax model to initialize\n config: config object\n rng: jax.prng key\n mesh: jax.devices() mesh\n checkpoint_manager: Checkpoint manager\n\n Returns:\n state: state with decode params loaded from the checkpoint\n state_mesh_annotations: the mesh annotations for the state\n """"""\n if not config.load_parameters_path:\n # generate random params\n max_logging.log(""No decode checkpoint specified - generating random weights."")\n state, state_mesh_annotations, _, _ = setup_initial_state(\n model, None, None, config, rng, mesh, checkpoint_manager, False\n )\n else:\n # Load params from checkpoint\n max_logging.log(f""Loading decode params from {config.load_parameters_path}"")\n unboxed_abstract_state, state_mesh_annotations, _ = get_abstract_state(model, None, config, rng, mesh, False)\n with nn_partitioning.axis_rules(config.logical_axis_rules):\n params = checkpointing.load_params_from_path(\n config.load_parameters_path,\n unboxed_abstract_state.params,\n config.checkpoint_storage_concurrent_gb,\n config.checkpoint_storage_use_ocdbt,\n config.checkpoint_storage_use_zarr3,\n )\n state = init_decode_state(None, params)\n\n state = max_utils.unbox_logicallypartioned(state)\n return state, state_mesh_annotations\n\n\ndef setup_training_state(model, data_iterator, tx, config, rng, mesh, checkpoint_manager):\n is_training = True\n return setup_initial_state(\n model,\n data_iterator,\n tx,\n config,\n rng,\n mesh,\n checkpoint_manager,\n is_training,\n )\n\n\ndef setup_initial_state(\n model,\n data_iterator,\n tx,\n config,\n rng,\n mesh,\n checkpoint_manager,\n is_training=True,\n):\n """"""We initialize the model and optimizer state, and optionally load from a\n checkpoint as necessary.\n\n Args:\n model: the flax model to initialize\n tx: the optax.GradientTransformation\n config: config object\n rng: jax.prng key\n mesh: jax.devices() mesh\n checkpoint_manager: an Orbax checkpointing.CheckpointManager object\n is_training: True to initialize training state, False for decode state\n\n Returns:\n state: the initialized train state\n state_mesh_annotations: the mesh annotations for the train state\n """"""\n\n unboxed_abstract_state, state_mesh_annotations, state_mesh_shardings = get_abstract_state(\n model, tx, config, rng, mesh, is_training\n )\n\n # Initialization\n with nn_partitioning.axis_rules(config.logical_axis_rules):\n restored, raw_params = checkpointing.load_state_if_possible(\n checkpoint_manager,\n data_iterator,\n config.load_parameters_path,\n config.load_full_state_path,\n config.checkpoint_storage_concurrent_gb,\n unboxed_abstract_state,\n config.enable_single_replica_ckpt_restoring,\n config.dataset_type,\n use_ocdbt=config.checkpoint_storage_use_ocdbt,\n use_zarr3=config.checkpoint_storage_use_zarr3,\n enable_orbax_v1=config.enable_orbax_v1,\n checkpoint_conversion_fn=config.checkpoint_conversion_fn,\n source_checkpoint_layout=config.source_checkpoint_layout,\n )\n\n if restored:\n if isinstance(\n checkpoint_manager,\n (\n emergency_checkpoint_manager.CheckpointManager,\n emergency_replicator_checkpoint_manager.ReplicatorCheckpointManager,\n ),\n ):\n state = restored\n else:\n if ""iter"" in restored and restored[""iter""] is not None:\n data_iterator.local_iterator = restored[""iter""]\n state = restored[""items""]\n else:\n init_state_partial = functools.partial(init_initial_state, model, tx, config, is_training)\n init_state_partial.__name__ = ""initialize_state""\n # pylint: disable=not-callable\n state = jax.jit(\n init_state_partial,\n in_shardings=None,\n out_shardings=state_mesh_shardings,\n )(rng)\n if raw_params: # If we loaded a partial state, we need to merge it.\n state = state.replace(params=raw_params)\n\n state = max_utils.unbox_logicallypartioned(state)\n\n return state, state_mesh_annotations, state_mesh_shardings, data_iterator\n\n\ndef get_abstract_state(model, tx, config, rng, mesh, is_training=True):\n """"""Get a shaped abstraction of the state (including optimizer)""""""\n init_state_partial = functools.partial(init_initial_state, model, tx, config, is_training, rng)\n\n with nn_partitioning.axis_rules(config.logical_axis_rules):\n abstract_state = jax.eval_shape(init_state_partial)\n\n state_logical_annotations = nn.get_partition_spec(abstract_state)\n\n state_mesh_shardings = nn.logical_to_mesh_sharding(state_logical_annotations, mesh, config.logical_axis_rules)\n if is_training and config.optimizer_memory_host_offload:\n opt_state = jax.tree_util.tree_map(lambda x: x.with_memory_kind(kind=""pinned_host""), state_mesh_shardings.opt_state)\n state_mesh_shardings = state_mesh_shardings.replace(opt_state=opt_state)\n if is_training and config.parameter_memory_host_offload:\n assert config.param_scan_axis == 0, ""You must set the scan axis 0 to enable parameter offloading.""\n\n def move(path, x):\n max_logging.log(f""max_utils.py: Moving {path} to host"")\n return x.with_memory_kind(kind=""pinned_host"")\n\n params = jax.tree_util.tree_map_with_path(move, state_mesh_shardings.params)\n state_mesh_shardings = state_mesh_shardings.replace(params=params)\n\n abstract_sharded_state = jax.jit(init_state_partial, in_shardings=None, out_shardings=state_mesh_shardings).eval_shape()\n\n unboxed_abstract_sharded_state = max_utils.unbox_logicallypartioned(abstract_sharded_state)\n # Initialization\n with mesh, nn_partitioning.axis_rules(config.logical_axis_rules):\n state_mesh_annotations = nn.logical_to_mesh(state_logical_annotations)\n return (\n unboxed_abstract_sharded_state,\n state_mesh_annotations,\n state_mesh_shardings,\n )\n\n\ndef get_prefill_kv_cache_annotations(model, config, rng, mesh, page_state: None | PageState = None):\n """"""Get a shaped abstraction of the state (including optimizer)""""""\n\n def init_kv_cache(model, config):\n input_shape = (\n config.global_batch_size_to_load,\n config.max_prefill_predict_length,\n )\n image_shape = get_dummy_image_shape_for_init(config)\n\n model_vars = model.init(\n {""params"": rng, ""dropout"": rng, ""aqt"": rng},\n jnp.ones(input_shape),\n jnp.ones(input_shape),\n encoder_images=jnp.ones(image_shape) if config.use_multimodal else None,\n model_mode=MODEL_MODE_PREFILL,\n slot=0,\n page_state=page_state,\n )\n return model_vars[""cache""]\n\n with nn_partitioning.axis_rules(config.logical_axis_rules):\n init_kv_cache_partial = functools.partial(init_kv_cache, model, config)\n abstract_state = jax.eval_shape(init_kv_cache_partial)\n state_logical_annotations = nn.get_partition_spec(abstract_state)\n with mesh, nn_partitioning.axis_rules(config.logical_axis_rules):\n state_mesh_annotations = nn.logical_to_mesh(state_logical_annotations)\n return state_mesh_annotations\n\n\ndef get_kv_cache_annotations(model, config, rng, mesh, page_state: None | PageState = None):\n """"""Get a shaped abstraction of the state (including optimizer)""""""\n\n def init_kv_cache(model, config):\n input_shape = (\n config.global_batch_size_to_load,\n 1,\n )\n image_shape = get_dummy_image_shape_for_init(config)\n\n model_vars = model.init(\n {""params"": rng, ""dropout"": rng, ""aqt"": rng},\n jnp.ones(input_shape),\n jnp.ones(input_shape),\n encoder_images=jnp.ones(image_shape) if config.use_multimodal else None,\n model_mode=MODEL_MODE_AUTOREGRESSIVE,\n slot=0,\n page_state=page_state,\n )\n return model_vars[""cache""]\n\n with nn_partitioning.axis_rules(config.logical_axis_rules):\n init_kv_cache_partial = functools.partial(init_kv_cache, model, config)\n abstract_state = jax.eval_shape(init_kv_cache_partial)\n state_logical_annotations = nn.get_partition_spec(abstract_state)\n with mesh, nn_partitioning.axis_rules(config.logical_axis_rules):\n state_mesh_annotations = nn.logical_to_mesh(state_logical_annotations)\n return state_mesh_annotations\n\n\ndef save_quantized_checkpoint_if_configured(config, params):\n """"""Save quantized checkpoint if configured""""""\n assert config.quantization, ""quantization must be configured""\n if config.save_quantized_params_path:\n checkpointing.save_params_to_path(\n checkpoint_dir=config.save_quantized_params_path,\n params=params,\n use_ocdbt=config.checkpoint_storage_use_ocdbt,\n use_zarr3=config.checkpoint_storage_use_zarr3,\n )\n else:\n max_logging.log(""Skipping saving quantized checkpoint as save_quantized_params_path is null."")\n\n\ndef add_config_to_summary_writer(config, summary_writer):\n """"""Writes config params to tensorboard""""""\n if jax.process_index() == 0:\n for key, value in config.get_keys().items():\n max_utils.add_text_to_summary_writer(key, str(value), summary_writer)\n\n\ndef logical_axis_rules_pp_act_as_dp(logical_rules):\n """"""Add stage as a physical axes before data for each rule, so stage acts just like data instead of PP.\n This is used when we want to pipeline only a subset of layers, and leave the rest like DP.\n """"""\n new_rules = []\n for key, physical_axes in logical_rules:\n if isinstance(physical_axes, str):\n physical_axes = (physical_axes,)\n else:\n physical_axes = tuple(physical_axes)\n new_physical_axes = tuple(axis for axis in physical_axes if axis != ""stage"")\n if ""data"" in new_physical_axes:\n data_idx = new_physical_axes.index(""data"")\n new_physical_axes = new_physical_axes[0:data_idx] + (""stage"",) + new_physical_axes[data_idx:]\n new_rules.append((key, new_physical_axes))\n return tuple(new_rules)\n\n\ndef create_device_mesh(config, devices=None):\n """"""Creates a device mesh with each slice in its own data parallel group. If there is only one slice, uses two replicas""""""\n if devices is None:\n devices = jax.devices()\n if config.subslice_shape and config.enable_single_controller and config.num_slices == 1:\n max_logging.log(f""Trying to create a subslice with shape: {config.subslice_shape}"")\n subslice_shape = tuple(int(x) for x in config.subslice_shape.split("",""))\n device_coords = [device.coords for device in devices]\n device_coords_np = np.array(device_coords)\n\n # Find the minimum coordinates to start the subslice\n min_coords = device_coords_np.min(axis=0)\n\n subslice_devices = []\n for device in devices:\n coords = device.coords\n if all(min_coords[i] <= coords[i] < min_coords[i] + subslice_shape[i] for i in range(len(subslice_shape))):\n subslice_devices.append(device)\n devices = subslice_devices\n\n num_devices = len(devices)\n num_slices = 1 if config.inference_benchmark_test else config.num_slices\n num_devices_per_slice = num_devices // num_slices\n\n multi_slice_env = num_slices > 1\n\n # Find possible unspecified parallelisms\n ici_parallelism = max_utils.fill_unspecified_mesh_axes(config.ici_parallelism.copy(), num_devices_per_slice, ""ICI"")\n\n allow_split_physical_axes = config.allow_split_physical_axes if config.allow_split_physical_axes else False\n\n if multi_slice_env:\n dcn_parallelism = max_utils.fill_unspecified_mesh_axes(config.dcn_parallelism.copy(), num_slices, ""DCN"")\n if max_utils.is_valid_custom_mesh(ici_parallelism, config.custom_mesh):\n mesh = max_utils.create_custom_device_mesh(ici_parallelism, dcn_parallelism, devices, config.custom_mesh)\n else:\n mesh = mesh_utils.create_hybrid_device_mesh(\n ici_parallelism,\n dcn_parallelism,\n devices,\n allow_split_physical_axes=allow_split_physical_axes,\n )\n else:\n if allow_split_physical_axes:\n if max_utils.is_valid_custom_mesh(ici_parallelism, config.custom_mesh):\n mesh = mesh_utils.create_device_mesh(\n [16, 16],\n devices,\n contiguous_submeshes=False,\n allow_split_physical_axes=False,\n )\n mesh = max_utils.reshape_mesh_to_rings(mesh, config.custom_mesh)\n mesh = np.reshape(mesh, ici_parallelism)\n else:\n mesh = mesh_utils.create_device_mesh(\n ici_parallelism,\n devices,\n contiguous_submeshes=False,\n allow_split_physical_axes=allow_split_physical_axes,\n )\n else:\n mesh = mesh_utils.create_device_mesh(\n ici_parallelism,\n devices,\n )\n if config.optimize_mesh_for_tpu_v6e:\n mesh = max_utils.optimize_mesh_for_tpu_v6e(mesh, devices)\n\n max_logging.log(f""Num_devices: {num_devices}, shape {mesh.shape}"")\n\n return mesh\n\n\n# Learning Rate Schedule\n# -----------------------------------------------------------------------------\n\n\ndef create_learning_rate_schedule(config):\n """"""Creates a warmup and cosine decay learning rate schedule:\n We take inspiration from Llama2's learning rate (LR) schedule, see https://arxiv.org/pdf/2307.09288.pdf section 2.2\n Learning rate schedule has either two or three parts:\n 1) Linear warmup from 0 to [learning_rate] over steps 0 to [learning_rate_schedule_steps * warmup_steps_fraction]\n 2) Cosine from [learning_rate] to [learning_rate * cosine_learning_rate_final_fraction] until learning_rate_schedule_steps\n 3) Constant learning rate of 0 from learning_rate_schedule_steps to steps.\n The zero learning rate section can be used to more accurately measure the fully trained model's performance.\n """"""\n\n def make_cos_schedule(init_lr, final_lr, len_steps):\n def schedule(step):\n pct = (step) / len_steps\n a = 0.5 * (jnp.cos(jnp.pi * pct) + 1)\n lr = init_lr * a + final_lr * (1 - a)\n return lr\n\n return schedule\n\n lr = config.learning_rate\n cos_final_lr = lr * config.cosine_learning_rate_final_fraction\n\n warmup_steps = int(config.learning_rate_schedule_steps * config.warmup_steps_fraction)\n cos_steps = config.learning_rate_schedule_steps - warmup_steps\n constant_zero_steps = config.steps - config.learning_rate_schedule_steps\n\n warmup_schedule = optax.linear_schedule(init_value=0.0, end_value=lr, transition_steps=warmup_steps)\n cos_schedule = make_cos_schedule(lr, cos_final_lr, cos_steps)\n constant_schedule = optax.constant_schedule(0.0)\n\n pieces = [warmup_schedule, cos_schedule]\n boundaries = [\n warmup_steps,\n warmup_steps + cos_steps,\n ]\n\n if constant_zero_steps > 0:\n pieces.append(constant_schedule)\n boundaries.append(warmup_steps + cos_steps + constant_zero_steps)\n\n return optax.join_schedules(pieces, boundaries)\n\n\ndef get_formatted_sharding_annotations(params, mesh=None):\n """"""\n Generates a readable string report of sharding annotations for all parameters.\n\n This function iterates through a PyTree of model parameters and inspects the\n sharding information attached to each parameter (leaf). It creates a\n human-readable summary that is useful for debugging sharding configurations.\n\n Args:\n params: The PyTree of model parameters to inspect.\n mesh: (Optional) The device mesh. If provided, its axis names and shape\n are included in the report for additional context.\n\n Returns:\n A single string containing the formatted report of sharding annotations\n for every parameter, with each entry on a new line.\n """"""\n # Initialize a list to hold the lines of the report, starting with a title.\n annotation_lines = [""Comprehensice Weight Sharding Annotations:""]\n\n # If a mesh object is provided, add its details to the report header.\n if mesh:\n annotation_lines.append(f""Mesh axes: {mesh.axis_names}, Mesh shape: {mesh.shape}"")\n annotation_lines.append(""-"" * 30)\n\n # Get a flattened list of all parameters (leaves) and their corresponding paths in the PyTree.\n all_params_leaves = jtu.tree_leaves_with_path(params)\n\n # Loop through each parameter leaf in the flattened list.\n for path, p_leaf in all_params_leaves:\n # Convert the parameter's path (a sequence of keys) into a readable string name.\n param_name_str = jtu.keystr(path)\n # Get the shape of the parameter as a string.\n shape_str = str(p_leaf.shape)\n # Set a default description for sharding, in case none is found.\n sharding_desc = ""N/A""\n\n # Check if the parameter leaf has a 'sharding' attribute.\n if hasattr(p_leaf, ""sharding""):\n # Case 1: Standard JAX sharding with a PartitionSpec.\n if hasattr(p_leaf.sharding, ""spec"") and p_leaf.sharding.spec is not None:\n # The spec is a tuple (PartitionSpec), format it for readability.\n spec_parts = []\n for item in p_leaf.sharding.spec:\n # Represent None as ""Replicated"" to make it explicit.\n spec_parts.append(str(item) if item is not None else ""Replicated"")\n sharding_desc = f""PartitionSpec({', '.join(spec_parts)})""\n # Case 2: The parameter is explicitly marked as fully replicated.\n elif hasattr(p_leaf.sharding, ""spec"") and p_leaf.sharding.spec is None:\n sharding_desc = ""Fully Replicated (spec is None)""\n # Case 3: A generic fallback if a sharding object exists but has no recognized spec attribute.\n else:\n # Print the string representation of the sharding object itself.\n sharding_desc = str(p_leaf.sharding)\n # Case 4: The parameter has no .sharding attribute at all.\n else:\n sharding_desc = ""No .sharding attribute found""\n\n # Append the formatted details for the current parameter to our list of lines.\n annotation_lines.append(f"" - Param: {param_name_str}\n"" f"" Shape: {shape_str}\n"" f"" Sharding: {sharding_desc}"")\n # Join all the collected lines into a single string, separated by newlines.\n return ""\n"".join(annotation_lines)\n\n\ndef get_physical_spec_no_fsdp(full_logical, mesh, logical_axis_rules):\n """"""\n Generates a physical sharding spec for fully replicated weights.\n\n This function computes a target sharding layout where model parameters are fully\n replicated across the 'fsdp' mesh axis. It starts with the original logical\n sharding and removes any rules that shard along the 'fsdp' or\n 'fsdp_transpose' axes.\n\n Replacing a sharding axis with `None` in a PartitionSpec instructs JAX to\n replicate the array data along that physical mesh dimension. The resulting\n specification is used as a target layout for an all-gather operation.\n\n Args:\n full_logical: A PyTree of logical PartitionSpecs for the model parameters.\n mesh: The JAX device mesh.\n logical_axis_rules: Rules for converting logical axes to physical mesh axes.\n\n Returns:\n A PyTree of physical `jax.sharding.NamedSharding` objects that describe a\n layout where parameters are fully gathered (replicated) across the 'fsdp'\n mesh axis.\n """"""\n\n def remove_fsdp_sharding(sharding_tree):\n """"""Recursively traverses the sharding tree to remove fsdp axes.""""""\n\n def _remove_fsdp_from_partition_spec(named_sharding):\n """"""Removes 'fsdp' and 'fsdp_transpose' from a PartitionSpec.""""""\n if isinstance(named_sharding, jax.sharding.NamedSharding):\n new_spec = []\n # Iterate through each axis in the original PartitionSpec.\n for axis in named_sharding.spec:\n if axis is None:\n new_spec.append(None)\n elif isinstance(axis, str):\n # If the axis is 'fsdp', replace it with None to signify replication.\n if axis not in (""fsdp"", ""fsdp_transpose""):\n new_spec.append(axis)\n else:\n new_spec.append(None)\n elif isinstance(axis, (list, tuple)):\n # If the axis is a collection, filter out 'fsdp'.\n new_axis = [a for a in axis if a not in (""fsdp"", ""fsdp_transpose"")]\n new_spec.append(tuple(new_axis))\n else:\n raise ValueError(f""Unsupported_axis_type: {type(axis)}"")\n # Return a new sharding object with the modified spec.\n return jax.sharding.NamedSharding(named_sharding.mesh, jax.sharding.PartitionSpec(*new_spec))\n return named_sharding\n\n return jax.tree.map(_remove_fsdp_from_partition_spec, sharding_tree)\n\n # Convert the high-level logical spec to a physical one using default rules.\n physical = nn.logical_to_mesh_sharding(full_logical, mesh=mesh, rules=logical_axis_rules)\n # Apply the function to remove the FSDP sharding, defining our target layout.\n physical_no_fsdp = remove_fsdp_sharding(physical)\n return physical_no_fsdp\n\n\ndef all_gather_over_fsdp(variables, sharding_info, mesh, logical_axis_rules):\n """"""Performs an all-gather on FSDP-sharded variables via a sharding constraint.\n This function triggers an all-gather operation on the model's parameters.\n It does so by applying a sharding constraint that specifies a fully\n replicated layout.\n\n The JAX compiler satisfies this constraint by automatically inserting the\n necessary `all-gather` collective communication operations into the\n computation graph, effectively gathering the sharded weights.\n\n Args:\n variables: The PyTree of model parameters, currently sharded across devices.\n sharding_info: The logical partition spec of the currently sharded `variables`.\n mesh: The JAX device mesh.\n logical_axis_rules: Rules for converting logical axes to physical mesh axes.\n\n Returns:\n The model's variables with the all-gather operation applied, resulting\n in the weights being fully replicated on all devices in the 'fsdp' mesh.\n """"""\n # Get the target physical layout (weights fully replicated).\n physical_constraint_no_fsdp = get_physical_spec_no_fsdp(sharding_info, mesh, logical_axis_rules)\n # Apply the constraint to the model's current variables. This tells JAX to\n # gather the weights into this layout.\n return jax.lax.with_sharding_constraint(variables, physical_constraint_no_fsdp)\n",python,tab
|
| 11 |
+
10,78032,"MaxText/maxtext_utils.py",2037,722,"def get_functional_train_with_signature(train_step, data_sharding, state_mesh_shardings, model, config):\n """"""Get the shardings (both state and data) for `train_step`.""""""\n functional_train = functools.partial(train_step, model, config, state_mesh_shardings)\n functional_train.__name__ = ""train_step""\n in_shardings = (state_mesh_shardings, data_sharding, None) # State, batch, rng\n out_shardings = (state_mesh_shardings, None) # State, metrics\n static_argnums = () # We partial out the static argnums of model and config\n donate_argnums = 0 # This is the index of the state - we allow the compiler to make use of this memory.\n return functional_train, in_shardings, out_shardings, static_argnums, donate_argnums\n",python,selection_command
|
| 12 |
+
11,80887,"MaxText/checkpointing.py",0,0,"",python,tab
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-61a8c6c4-3944-4cce-817c-d7f3d58f5a4d1764870580114-2025_12_04-18.49.46.89/source.csv
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Sequence,Time,File,RangeOffset,RangeLength,Text,Language,Type
|
| 2 |
+
1,3,"src/extension.ts",0,0,"import * as vscode from 'vscode';\nimport * as https from 'https';\nimport * as http from 'http';\nimport { Buffer } from 'buffer';\n\n\nconst SGLANG_HOSTNAME = 'hai007';\nconst SGLANG_PORT = 30000;\nconst SGLANG_BASE_PATH = '/v1/chat/completions';\nconst SGLANG_MODEL_NAME = 'qwen/qwen3-0.6b';\n\nconst GEMINI_HOSTNAME = 'generativelanguage.googleapis.com';\nconst GEMINI_PORT = 443;\nconst GEMINI_BASE_PATH = '/v1beta/openai/chat/completions';\nconst GEMINI_MODEL_NAME = 'gemini-2.5-flash';\n\nconst USE_GEMINI = false;\n\nexport function activate(context: vscode.ExtensionContext) {\n\n\tconsole.log('[crowd-pilot] Extension activated');\n\n\t// Configure terminal to allow tab keybinding to work\n\t(async () => {\n\t\tconst config = vscode.workspace.getConfiguration('terminal.integrated');\n\t\tconst commandsToSkipShell = config.get<string[]>('commandsToSkipShell', []);\n\t\tlet updated = false;\n\t\tif (!commandsToSkipShell.includes('crowd-pilot.modelRun')) {\n\t\t\tcommandsToSkipShell.push('crowd-pilot.modelRun');\n\t\t\tupdated = true;\n\t\t}\n\t\tif (!commandsToSkipShell.includes('crowd-pilot.hideUi')) {\n\t\t\tcommandsToSkipShell.push('crowd-pilot.hideUi');\n\t\t\tupdated = true;\n\t\t}\n\t\tif (updated) {\n\t\t\tawait config.update('commandsToSkipShell', commandsToSkipShell, vscode.ConfigurationTarget.Global);\n\t\t}\n\t})().catch((err) => console.error('[crowd-pilot] Startup initialization error:', err));\n\n\tconst hideUi = vscode.commands.registerCommand('crowd-pilot.hideUi', () => {\n\t\thidePreviewUI(true);\n\t});\n\n\tconst modelRun = vscode.commands.registerCommand('crowd-pilot.modelRun', async () => {\n\t\tconst editor = vscode.window.activeTextEditor;\n\t\tif (!editor) {\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\t// Confirm only when a suggestion is visible\n\t\t\tif (!previewVisible) { return; }\n\t\t\tlet action: PlannedAction | undefined = currentAction;\n\t\t\tif (!action) {\n\t\t\t\tconst single = await requestModelActions(editor);\n\t\t\t\tcurrentAction = single;\n\t\t\t\taction = single;\n\t\t\t}\n\t\t\tif (!action) {\n\t\t\t\thidePreviewUI();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\thidePreviewUI(false);\n\t\t\tawait executeAction(action);\n\t\t\tautoShowNextAction();\n\t\t} catch (err) {\n\t\t\tconst errorMessage = err instanceof Error ? err.message : String(err);\n\t\t\tvscode.window.showErrorMessage(`Model run failed: ${errorMessage}`);\n\t\t}\n\t});\n\n\tconst sglangTest = vscode.commands.registerCommand('crowd-pilot.sglangTest', async () => {\n\t\ttry {\n\t\t\tawait callSGLangChat();\n\t\t} catch (err) {\n\t\t\tconst errorMessage = err instanceof Error ? err.message : String(err);\n\t\t\tvscode.window.showErrorMessage(`SGLang test failed: ${errorMessage}`);\n\t\t}\n\t});\n\n\t// Auto-preview listeners\n\tconst debouncedAutoPreview = debounce(() => {\n\t\tautoShowNextAction();\n\t}, 250);\n\tconst onSelChange = vscode.window.onDidChangeTextEditorSelection((e) => {\n\t\tif (e.textEditor === vscode.window.activeTextEditor) {\n\t\t\tsuppressAutoPreview = false;\n\t\t\tdebouncedAutoPreview();\n\t\t}\n\t});\n\tconst onActiveChange = vscode.window.onDidChangeActiveTextEditor(() => {\n\t\tsuppressAutoPreview = false;\n\t\tdebouncedAutoPreview();\n\t});\n\tconst onDocChange = vscode.workspace.onDidChangeTextDocument((e) => {\n\t\tif (vscode.window.activeTextEditor?.document === e.document) {\n\t\t\tsuppressAutoPreview = false;\n\t\t\tdebouncedAutoPreview();\n\t\t}\n\t});\n\n\tcontext.subscriptions.push(hideUi, sglangTest, modelRun, onSelChange, onActiveChange, onDocChange);\n}\n\nexport function deactivate() {}\n\n// -------------------- Plan Types & Execution --------------------\ntype PlannedAction =\n| { kind: 'showTextDocument' }\n| { kind: 'setSelections', selections: Array<{ start: [number, number], end: [number, number] }> }\n| { kind: 'editInsert', position: [number, number], text: string }\n| { kind: 'editDelete', range: { start: [number, number], end: [number, number] } }\n| { kind: 'editReplace', range: { start: [number, number], end: [number, number] }, text: string }\n| { kind: 'terminalShow' }\n| { kind: 'terminalSendText', text: string };\n\nlet currentAction: PlannedAction | undefined;\n\nasync function executeAction(action: PlannedAction): Promise<void> {\n\tconst editor = vscode.window.activeTextEditor;\n\tif (!editor) { return; }\n\tconst doc = editor.document;\n\tconst term = vscode.window.terminals[0] ?? vscode.window.createTerminal('Test');\n\tif (action.kind === 'showTextDocument') {\n\t\tawait vscode.window.showTextDocument(doc);\n\t\treturn;\n\t}\n\tif (action.kind === 'setSelections') {\n\t\teditor.selections = action.selections.map(s => new vscode.Selection(\n\t\t\tnew vscode.Position(s.start[0], s.start[1]),\n\t\t\tnew vscode.Position(s.end[0], s.end[1])\n\t\t));\n\t\tif (editor.selections.length > 0) {\n\t\t\teditor.revealRange(editor.selections[0], vscode.TextEditorRevealType.InCenterIfOutsideViewport);\n\t\t}\n\t\treturn;\n\t}\n\tif (action.kind === 'editInsert') {\n\t\tawait editor.edit((e: vscode.TextEditorEdit) => e.insert(new vscode.Position(action.position[0], action.position[1]), action.text));\n\t\treturn;\n\t}\n\tif (action.kind === 'editDelete') {\n\t\tconst range = new vscode.Range(\n\t\t\tnew vscode.Position(action.range.start[0], action.range.start[1]),\n\t\t\tnew vscode.Position(action.range.end[0], action.range.end[1])\n\t\t);\n\t\tawait editor.edit((e: vscode.TextEditorEdit) => e.delete(range));\n\t\treturn;\n\t}\n\tif (action.kind === 'editReplace') {\n\t\tconst range = new vscode.Range(\n\t\t\tnew vscode.Position(action.range.start[0], action.range.start[1]),\n\t\t\tnew vscode.Position(action.range.end[0], action.range.end[1])\n\t\t);\n\t\tawait editor.edit((e: vscode.TextEditorEdit) => e.replace(range, action.text));\n\t\treturn;\n\t}\n\tif (action.kind === 'terminalShow') {\n\t\tterm.show();\n\t\treturn;\n\t}\n\tif (action.kind === 'terminalSendText') {\n\t\tterm.sendText(action.text);\n\t\treturn;\n\t}\n}\n\n// -------------------- UI State & Helpers --------------------\nconst UI_CONTEXT_KEY = 'crowdPilot.uiVisible';\nlet previewVisible = false;\nlet decorationDeleteType: vscode.TextEditorDecorationType | undefined;\nlet decorationReplaceType: vscode.TextEditorDecorationType | undefined;\nlet decorationReplaceBlockType: vscode.TextEditorDecorationType | undefined;\nlet mockStep = 0;\nlet suppressAutoPreview = false;\nlet latestRequestId = 0;\nlet currentAbortController: AbortController | undefined;\n\nfunction disposePreviewDecorations() {\n\ttry { decorationDeleteType?.dispose(); } catch {}\n\ttry { decorationReplaceType?.dispose(); } catch {}\n\ttry { decorationReplaceBlockType?.dispose(); } catch {}\n\tdecorationDeleteType = undefined;\n\tdecorationReplaceType = undefined;\n\tdecorationReplaceBlockType = undefined;\n}\n\nfunction debounce<T extends (...args: any[]) => void>(fn: T, waitMs: number) {\n\tlet timer: NodeJS.Timeout | undefined;\n\treturn (...args: Parameters<T>) => {\n\t\tif (timer) { clearTimeout(timer); }\n\t\ttimer = setTimeout(() => fn(...args), waitMs);\n\t};\n}\n\nfunction getDynamicMargin(editor: vscode.TextEditor, anchorLine: number, text: string): string {\n\t// Count lines in the preview text\n\tconst lines = text.split(/\r?\n/);\n\tconst height = lines.length;\n\t\n\t// We need to check the document lines that will be covered by this panel.\n\t// The panel starts at 'anchorLine' and extends downwards by 'height' lines.\n\t// However, visually, since it's 'after', it sits to the right of 'anchorLine',\n\t// and then flows down.\n\t// So we check document lines from anchorLine to anchorLine + height - 1.\n\t\n\tconst doc = editor.document;\n\tlet maxLen = 0;\n\tconst startLine = anchorLine;\n\tconst endLine = Math.min(doc.lineCount - 1, anchorLine + height - 1);\n\t\n\tfor (let i = startLine; i <= endLine; i++) {\n\t\tconst lineText = doc.lineAt(i).text;\n\t\t// Simple approximation: assume tabs are 4 spaces if we can't get config easily, \n\t\t// or just treat them as 1 char (which might underestimate). \n\t\t// Better to overestimate: treat tab as 4 chars.\n\t\tconst len = lineText.replace(/\t/g, ' ').length;\n\t\tif (len > maxLen) {\n\t\t\tmaxLen = len;\n\t\t}\n\t}\n\t\n\t// Length of the anchor line itself\n\tconst anchorLineText = doc.lineAt(anchorLine).text;\n\tconst anchorLen = anchorLineText.replace(/\t/g, ' ').length;\n\t\n\t// The offset needed is maxLen - anchorLen.\n\t// If maxLen <= anchorLen, offset is 0 (margin is just base padding).\n\t// If maxLen > anchorLen, we need to push right by (maxLen - anchorLen).\n\t\n\tconst diff = Math.max(0, maxLen - anchorLen);\n\t// Base margin 2rem is roughly 4ch. Let's use ch units for everything to be consistent.\n\t// 1ch is width of '0'. In monospace, mostly consistent.\n\t// Add 3ch extra padding for safety/visual gap.\n\tconst margin = diff + 4; \n\treturn `${margin}ch`;\n}\n\nfunction showPreviewUI(action: PlannedAction): void {\n\tconst editor = vscode.window.activeTextEditor;\n\tif (!editor) { return; }\n\tdisposePreviewDecorations();\n\n\t// FIXME (f.srambical): add file switch \n\tconst next = (action.kind === 'editInsert' || action.kind === 'editDelete' || action.kind === 'editReplace' || action.kind === 'terminalSendText' || action.kind === 'setSelections') ? action : undefined;\n\tif (!next) {\n\t\tpreviewVisible = false;\n\t\tvscode.commands.executeCommand('setContext', UI_CONTEXT_KEY, false);\n\t\tcurrentAction = action;\n\t\treturn;\n\t}\n\n\tconst trimText = (t: string) => {\n\t\tconst oneLine = t.replace(/\r?\n/g, '\\n');\n\t\treturn oneLine.length > 80 ? oneLine.slice(0, 77) + '…' : oneLine;\n\t};\n\n\tif (next.kind === 'setSelections') {\n\t\t// For setSelections, we only preview the primary selection's start/active position\n\t\tconst selection = next.selections[0];\n\t\tconst targetPos = new vscode.Position(selection.start[0], selection.start[1]);\n\t\t// Check if the target position is visible\n\t\tconst isVisible = editor.visibleRanges.some(r => r.contains(targetPos));\n\t\t\n\t\tlet anchorPos = targetPos;\n\t\tlet label = ""↳ Move Cursor Here"";\n\n\t\tif (!isVisible && editor.visibleRanges.length > 0) {\n\t\t\tconst firstVisible = editor.visibleRanges[0].start;\n\t\t\tconst lastVisible = editor.visibleRanges[editor.visibleRanges.length - 1].end;\n\t\t\t\n\t\t\tif (targetPos.isBefore(firstVisible)) {\n\t\t\t\tanchorPos = editor.document.lineAt(firstVisible.line).range.end;\n\t\t\t} else {\n\t\t\t\tanchorPos = editor.document.lineAt(lastVisible.line).range.end;\n\t\t\t}\n\n\t\t\tif (targetPos.line < anchorPos.line) {\n\t\t\t\tlabel = `↑ Move Cursor to Line ${targetPos.line + 1}`;\n\t\t\t} else {\n\t\t\t\tlabel = `↓ Move Cursor to Line ${targetPos.line + 1}`;\n\t\t\t}\n\t\t}\n\n\t\tconst margin = getDynamicMargin(editor, anchorPos.line, label);\n\n\t\tdecorationReplaceBlockType = vscode.window.createTextEditorDecorationType({\n\t\t\tafter: {\n\t\t\t\tcontentText: '',\n\t\t\t\tcolor: new vscode.ThemeColor('charts.purple'),\n\t\t\t\tbackgroundColor: new vscode.ThemeColor('editor.background'),\n\t\t\t\tfontStyle: 'italic',\n\t\t\t\tfontWeight: '600',\n\t\t\t\tmargin: `0 0 0 ${margin}`,\n\t\t\t\ttextDecoration: `none; display: inline-block; white-space: pre; content: ""${label}""; border: 1px solid var(--vscode-charts-purple); padding: 4px; border-radius: 4px; box-shadow: 0 4px 8px rgba(0,0,0,0.25); pointer-events: none; position: relative; z-index: 100; vertical-align: top;`\n\t\t\t}\n\t\t});\n\t\teditor.setDecorations(decorationReplaceBlockType, [{ range: new vscode.Range(anchorPos, anchorPos) }]);\n\t} else if (next.kind === 'terminalSendText') {\n\t\tconst cursor = editor.selection.active;\n\t\tconst lineEnd = editor.document.lineAt(cursor.line).range.end;\n\t\tconst summary = trimText(next.text || '');\n\t\tconst label = `↳ Execute shell command in terminal: ${summary}`;\n\t\tconst margin = getDynamicMargin(editor, cursor.line, label);\n\n\t\tdecorationReplaceBlockType = vscode.window.createTextEditorDecorationType({\n\t\t\tafter: {\n\t\t\t\tcontentText: '',\n\t\t\t\tcolor: new vscode.ThemeColor('charts.purple'),\n\t\t\t\tbackgroundColor: new vscode.ThemeColor('editor.background'),\n\t\t\t\tfontStyle: 'italic',\n\t\t\t\tfontWeight: '600',\n\t\t\t\tmargin: `0 0 0 ${margin}`,\n\t\t\t\ttextDecoration: `none; display: inline-block; white-space: pre; content: ""${label.replace(/""/g, '\\""')}""; border: 1px solid var(--vscode-charts-purple); padding: 4px; border-radius: 4px; box-shadow: 0 4px 8px rgba(0,0,0,0.25); pointer-events: none; position: relative; z-index: 100; vertical-align: top;`\n\t\t\t}\n\t\t});\n\t\teditor.setDecorations(decorationReplaceBlockType, [{ range: new vscode.Range(lineEnd, lineEnd) }]);\n\t} else if (next.kind === 'editInsert') {\n\t\tconst posLine = next.position[0];\n\t\tconst fullBlock = next.text;\n\t\tconst cssContent = fullBlock\n\t\t\t.replace(/""/g, '\\""')\n\t\t\t.replace(/\r?\n/g, '\\A ');\n\n\t\tconst docLineCount = editor.document.lineCount;\n\t\t// If inserting at EOF (or beyond), attach to the last line.\n\t\t// Otherwise, attach to the line AT the insertion point and shift visually UP into the gap.\n\t\tlet anchorLine = posLine;\n\t\tlet shiftUp = true;\n\t\t\n\t\tif (anchorLine >= docLineCount) {\n\t\t\tanchorLine = docLineCount - 1;\n\t\t\tshiftUp = false; // At EOF, we just append below or to the right\n\t\t}\n\n\t\tconst anchorPos = new vscode.Position(anchorLine, Number.MAX_VALUE); \n\t\t\n\t\t// We attach to the line AT the insertion point.\n\t\t// The panel floats to the right of this line.\n\t\t// The dashed line connects the start of this line to the panel.\n\t\t// This indicates that the new text will be inserted at this line position (pushing the current line down).\n\t\tconst marginCheckLine = anchorLine;\n\t\tconst margin = getDynamicMargin(editor, marginCheckLine, fullBlock);\n\n\t\tconst topOffset = '0';\n\n\t\t// Dashed line style\n\t\t// We use 'before' decoration for the line.\n\t\t// It needs to be absolute, full width (or enough to reach left), \n\t\t// and aligned with the panel top.\n\t\tconst beforeDecoration = {\n\t\t\tcontentText: '',\n\t\t\ttextDecoration: `none; position: absolute; left: 0; width: 100vw; border-top: 1px dashed var(--vscode-charts-purple); top: 0; height: 0; z-index: 99; pointer-events: none;`\n\t\t};\n\n\t\tdecorationReplaceBlockType = vscode.window.createTextEditorDecorationType({\n\t\t\tbefore: beforeDecoration,\n\t\t\tafter: {\n\t\t\t\tcontentText: '',\n\t\t\t\tcolor: new vscode.ThemeColor('charts.purple'),\n\t\t\t\tbackgroundColor: new vscode.ThemeColor('editor.background'),\n\t\t\t\tfontStyle: 'italic',\n\t\t\t\tfontWeight: '600',\n\t\t\t\tmargin: `0 0 0 ${margin}`,\n\t\t\t\ttextDecoration: `none; display: inline-block; white-space: pre; content: ""${cssContent}""; border: 1px solid var(--vscode-charts-purple); padding: 4px; border-radius: 4px; box-shadow: 0 4px 8px rgba(0,0,0,0.25); pointer-events: none; position: relative; z-index: 100; vertical-align: top; top: ${topOffset};`\n\t\t\t}\n\t\t});\n\t\teditor.setDecorations(decorationReplaceBlockType, [{ range: new vscode.Range(anchorPos, anchorPos) }]);\n\t} else if (next.kind === 'editDelete') {\n\t\tconst range = new vscode.Range(\n\t\t\tnew vscode.Position(next.range.start[0], next.range.start[1]),\n\t\t\tnew vscode.Position(next.range.end[0], next.range.end[1])\n\t\t);\n\t\tdecorationDeleteType = vscode.window.createTextEditorDecorationType({\n\t\t\tbackgroundColor: 'rgba(255, 60, 60, 0.18)',\n\t\t\tborder: '1px solid rgba(255, 60, 60, 0.35)',\n\t\t\ttextDecoration: 'line-through'\n\t\t});\n\t\teditor.setDecorations(decorationDeleteType, [{ range }]);\n\t} else if (next.kind === 'editReplace') {\n\t\tconst range = new vscode.Range(\n\t\t\tnew vscode.Position(next.range.start[0], next.range.start[1]),\n\t\t\tnew vscode.Position(next.range.end[0], next.range.end[1])\n\t\t);\n\t\t// Highlight original range (to be replaced)\n\t\tdecorationReplaceType = vscode.window.createTextEditorDecorationType({\n\t\t\tbackgroundColor: 'rgba(255,165,0,0.15)',\n\t\t\tborder: '1px dashed rgba(255,165,0,0.45)',\n\t\t\tcolor: new vscode.ThemeColor('disabledForeground'),\n\t\t\ttextDecoration: 'line-through'\n\t\t});\n\t\teditor.setDecorations(decorationReplaceType, [{ range }]);\n\n\t\t// Show replacement block to the right of the first replaced line\n\t\tconst fullBlock = next.text;\n\t\t\n\t\t// CSS-escape the text for the 'content' property:\n\t\t// - Escape double quotes\n\t\t// - Replace newlines with \A (CSS newline)\n\t\tconst cssContent = fullBlock\n\t\t\t.replace(/""/g, '\\""')\n\t\t\t.replace(/\r?\n/g, '\\A '); \n\n\t\t// Attach 'after' decoration to the start of the replacement range\n\t\t// (Actually, attaching to the end of the first line is safer for 'after')\n\t\tconst anchorLine = range.start.line;\n\t\tconst anchorPos = new vscode.Position(anchorLine, Number.MAX_VALUE);\n\t\tconst margin = getDynamicMargin(editor, anchorLine, fullBlock);\n\n\t\tdecorationReplaceBlockType = vscode.window.createTextEditorDecorationType({\n\t\t\tafter: {\n\t\t\t\tcontentText: '', // Handled by CSS content\n\t\t\t\tcolor: new vscode.ThemeColor('charts.purple'),\n\t\t\t\tbackgroundColor: new vscode.ThemeColor('editor.background'),\n\t\t\t\tfontStyle: 'italic',\n\t\t\t\tfontWeight: '600',\n\t\t\t\tmargin: `0 0 0 ${margin}`,\n\t\t\t\ttextDecoration: `none; display: inline-block; white-space: pre; content: ""${cssContent}""; border: 1px solid var(--vscode-charts-purple); padding: 4px; border-radius: 4px; box-shadow: 0 4px 8px rgba(0,0,0,0.25); pointer-events: none; position: relative; z-index: 100; vertical-align: top;`\n\t\t\t}\n\t\t});\n\t\teditor.setDecorations(decorationReplaceBlockType, [{ range: new vscode.Range(anchorPos, anchorPos) }]);\n\t}\n\n\tpreviewVisible = true;\n\tvscode.commands.executeCommand('setContext', UI_CONTEXT_KEY, true);\n\tcurrentAction = action;\n}\n\nfunction hidePreviewUI(suppress?: boolean): void {\n\tdisposePreviewDecorations();\n\tpreviewVisible = false;\n\tvscode.commands.executeCommand('setContext', UI_CONTEXT_KEY, false);\n\tif (suppress) {\n\t\tsuppressAutoPreview = true;\n\t}\n}\n\n// -------------------- Hardcoded single-step actions --------------------\nfunction getHardcodedNextAction(editor: vscode.TextEditor): PlannedAction | undefined {\n\tconst cursor = editor.selection.active;\n\tconst doc = editor.document;\n\tconst lineCount = doc.lineCount;\n\tconst clamp = (n: number, min: number, max: number) => Math.max(min, Math.min(max, n));\n\n\t// Step 0: Insert multiline content two lines below the cursor (start of target line)\n\tif (mockStep === 0) {\n\t\tconst targetLine = clamp(cursor.line + 2, 0, Math.max(0, lineCount - 1));\n\t\treturn {\n\t\t\tkind: 'editInsert',\n\t\t\tposition: [targetLine, 0],\n\t\t\ttext: '/* crowd-pilot: insert start */\nline A\nline B\n/* crowd-pilot: insert end */\n'\n\t\t};\n\t}\n\t// Step 1: Replace a two-line range three and four lines below the cursor\n\tif (mockStep === 1) {\n\t\tconst startLine = clamp(cursor.line + 3, 0, Math.max(0, lineCount - 1));\n\t\tconst endLine = clamp(startLine + 1, 0, Math.max(0, lineCount - 1));\n\t\tconst endChar = doc.lineAt(endLine).range.end.character;\n\t\tconst range = {\n\t\t\tstart: [startLine, 0] as [number, number],\n\t\t\tend: [endLine, endChar] as [number, number]\n\t\t};\n\t\tconst replacement = [\n\t\t\t'/* crowd-pilot: replacement */',\n\t\t\t'REPLACED LINE 1',\n\t\t\t'REPLACED LINE 2'\n\t\t].join('\n');\n\t\treturn { kind: 'editReplace', range, text: replacement };\n\t}\n\t// Step 2: Delete a three-line range six to eight lines below the cursor\n\tif (mockStep === 2) {\n\t\tconst startLine = clamp(cursor.line + 6, 0, Math.max(0, lineCount - 1));\n\t\tconst endLine = clamp(startLine + 2, 0, Math.max(0, lineCount - 1));\n\t\t\n\t\t// To fully delete the lines including the newline, we target the start of the next line.\n\t\tlet endPosLine = endLine + 1;\n\t\tlet endPosChar = 0;\n\t\t\n\t\tif (endPosLine >= lineCount) {\n\t\t\t// If deleting the last line(s), just go to the end of the document\n\t\t\tendPosLine = lineCount - 1;\n\t\t\tendPosChar = doc.lineAt(endPosLine).range.end.character;\n\t\t}\n\n\t\tconst range = {\n\t\t\tstart: [startLine, 0] as [number, number],\n\t\t\tend: [endPosLine, endPosChar] as [number, number]\n\t\t};\n\t\treturn { kind: 'editDelete', range };\n\t}\n\t// Step 3: Execute in Terminal\n\tif (mockStep === 3) {\n\t\treturn { kind: 'terminalSendText', text: 'echo ""Hello World""' };\n\t}\n\t// Step 4: Move Cursor to End of File\n\tif (mockStep === 4) {\n\t\tconst lastLine = doc.lineCount - 1;\n\t\tconst lastChar = doc.lineAt(lastLine).range.end.character;\n\t\treturn {\n\t\t\tkind: 'setSelections',\n\t\t\tselections: [{ start: [lastLine, lastChar], end: [lastLine, lastChar] }]\n\t\t};\n\t}\n\treturn undefined;\n}\n\nfunction advanceMockStep(): void {\n\tmockStep = (mockStep + 1) % 5;\n}\n\nasync function autoShowNextAction(): Promise<void> {\n\tif (suppressAutoPreview) { return; }\n\tconst editor = vscode.window.activeTextEditor;\n\tif (!editor) { return; }\n\ttry {\n\t\tcurrentAbortController?.abort();\n\t\tconst controller = new AbortController();\n\t\tcurrentAbortController = controller;\n\t\tconst requestId = ++latestRequestId;\n\t\tconst next = await requestModelActions(editor, controller.signal);\n\t\tif (requestId !== latestRequestId) { return; }\n\t\tif (next) { showPreviewUI(next); } else { hidePreviewUI(); }\n\t} catch (err) {\n\t\tconst e = err as any;\n\t\tconst isAbort = e?.name === 'AbortError' || /aborted/i.test(String(e?.message ?? ''));\n\t\tif (isAbort) { return; }\n\t\thidePreviewUI();\n\t}\n}\n\n// -------------------- SGLang Client (simple test) --------------------\nasync function callSGLangChat(): Promise<void> {\n\tconst config = vscode.workspace.getConfiguration();\n\t\n\tlet hostname: string;\n\tlet port: number;\n\tlet path: string;\n\tlet useHttps = true;\n\tlet modelName: string;\n\tconst headers: any = {\n\t\t'Content-Type': 'application/json'\n\t};\n\n\tif (!USE_GEMINI) {\n\t\t// SGLang\n\t\thostname = SGLANG_HOSTNAME;\n\t\tport = SGLANG_PORT;\n\t\tpath = SGLANG_BASE_PATH;\n\t\tuseHttps = false; \n\t\tmodelName = SGLANG_MODEL_NAME;\n\t} else {\n\t\t// Gemini\n\t\tconst apiKey = config.get<string>('crowd-pilot.apiKey');\n\t\tif (!apiKey) {\n\t\t\tvscode.window.showErrorMessage('Crowd Pilot: Please set your API Key in settings (crowd-pilot.apiKey).');\n\t\t\treturn;\n\t\t}\n\t\thostname = GEMINI_HOSTNAME;\n\t\tport = GEMINI_PORT;\n\t\tpath = GEMINI_BASE_PATH;\n\t\theaders['Authorization'] = `Bearer ${apiKey}`;\n\t\tmodelName = GEMINI_MODEL_NAME;\n\t}\n\n\tconst requestBody: any = {\n\t\tmodel: modelName,\n\t\tmessages: [\n\t\t\t{ role: 'user', content: 'What is the capital of France?' }\n\t\t]\n\t};\n\tif (!USE_GEMINI) {\n\t\trequestBody.temperature = 0.7;\n\t\trequestBody.top_p = 0.8;\n\t\trequestBody.top_k = 20;\n\t\trequestBody.min_p = 0;\n\t\trequestBody.extra_body = {\n\t\t\tchat_template_kwargs: {\n\t\t\t\tenable_thinking: false\n\t\t\t}\n\t\t};\n\t}\n\tconst postData = JSON.stringify(requestBody);\n\theaders['Content-Length'] = Buffer.byteLength(postData);\n\n\tconst options = {\n\t\thostname,\n\t\tport,\n\t\tpath,\n\t\tmethod: 'POST',\n\t\theaders\n\t};\n\n\tconst requestModule = useHttps ? https : http;\n\n\ttry {\n\t\tconst json = await new Promise<any>((resolve, reject) => {\n\t\t\tconst req = requestModule.request(options, (res: http.IncomingMessage) => {\n\t\t\t\tlet data = '';\n\t\t\t\tres.on('data', (chunk: Buffer) => {\n\t\t\t\t\tdata += chunk.toString();\n\t\t\t\t});\n\t\t\t\tres.on('end', () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresolve(JSON.parse(data));\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\treject(new Error(`Failed to parse response: ${err instanceof Error ? err.message : String(err)}`));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\n\t\t\treq.on('error', (err: Error) => {\n\t\t\t\treject(err);\n\t\t\t});\n\n\t\t\treq.write(postData);\n\t\t\treq.end();\n\t\t});\n\n\t\tvscode.window.showInformationMessage(`Response: ${JSON.stringify(json, null, 2)}`);\n\t} catch (err) {\n\t\tconst errorMessage = err instanceof Error ? err.message : String(err);\n\t\tvscode.window.showErrorMessage(`Request failed: ${errorMessage}`);\n\t}\n}\n\n// -------------------- Prompt Serialization Helpers --------------------\nfunction formatStdoutBlock(content: string): string {\n\tconst normalized = content ?? '';\n\treturn `<stdout>\n${normalized}\n</stdout>`;\n}\n\nfunction formatLineNumberedOutput(content: string, startLine?: number, endLine?: number): string {\n\tconst lines = content.split(/\r?\n/);\n\tconst total = (lines.length === 1 && lines[0] === '') ? 0 : lines.length;\n\tif (total === 0) {\n\t\treturn '';\n\t}\n\tconst s = startLine !== undefined ? Math.max(1, Math.min(startLine, total)) : 1;\n\tconst e = endLine !== undefined ? Math.max(s, Math.min(endLine, total)) : total;\n\tconst buf: string[] = [];\n\tfor (let idx = s; idx <= e; idx++) {\n\t\tconst lineText = lines[idx - 1] ?? '';\n\t\tbuf.push(`${idx.toString().padStart(6, ' ')}\t${lineText}`);\n\t}\n\treturn buf.join('\n');\n}\n\nfunction computeViewport(totalLines: number, centerLine: number, radius: number): { start: number; end: number } {\n\tif (totalLines <= 0) {\n\t\treturn { start: 1, end: 0 };\n\t}\n\tconst start = Math.max(1, centerLine - radius);\n\tconst end = Math.min(totalLines, centerLine + radius);\n\treturn { start, end };\n}\n\nfunction fencedBashBlock(command: string): string {\n\tconst cleaned = command.replace(/\r/g, '').trim();\n\treturn `\`\`\`bash\n${cleaned}\n\`\`\``;\n}\n\n// -------------------- Model-planned Actions --------------------\nasync function requestModelActions(editor: vscode.TextEditor, signal?: AbortSignal): Promise<PlannedAction> {\n\tconst config = vscode.workspace.getConfiguration();\n\t\n\tlet hostname: string;\n\tlet port: number;\n\tlet path: string;\n\tlet useHttps = true;\n\tlet modelName: string;\n\tconst headers: any = {\n\t\t'Content-Type': 'application/json'\n\t};\n\n\tif (!USE_GEMINI) {\n\t\t// SGLang\n\t\thostname = SGLANG_HOSTNAME;\n\t\tport = SGLANG_PORT;\n\t\tpath = SGLANG_BASE_PATH;\n\t\tuseHttps = false;\n\t\tmodelName = SGLANG_MODEL_NAME;\n\t} else {\n\t\t// Gemini\n\t\tconst apiKey = config.get<string>('crowd-pilot.apiKey');\n\t\tif (!apiKey) {\n\t\t\tvscode.window.showErrorMessage('Crowd Pilot: Please set your API Key in settings (crowd-pilot.apiKey).');\n\t\t\tthrow new Error('API key not set');\n\t\t}\n\t\thostname = GEMINI_HOSTNAME;\n\t\tport = GEMINI_PORT;\n\t\tpath = GEMINI_BASE_PATH;\n\t\theaders['Authorization'] = `Bearer ${apiKey}`;\n\t\tmodelName = GEMINI_MODEL_NAME;\n\t}\n\n\tconst doc = editor.document;\n\tconst cursor = editor.selection.active;\n\tconst fullText = doc.getText();\n\tconst filePath = doc.uri.fsPath;\n\tconst workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath ?? '(unknown)';\n\tconst cursorLine = cursor.line + 1;\n\tconst cursorColumn = cursor.character + 1;\n\tconst totalLines = doc.lineCount;\n\tconst viewport = computeViewport(totalLines, cursorLine, 12);\n\tconst metadataSummary = [\n\t\t`Workspace root: ${workspaceRoot}`,\n\t\t`Active file: ${filePath}`,\n\t\t`Language: ${doc.languageId}`,\n\t\t`Cursor (1-based): line ${cursorLine}, column ${cursorColumn}`\n\t].join('\n');\n\tconst metadataCommand = [\n\t\t""cat <<'EOF'"",\n\t\tmetadataSummary,\n\t\t'EOF'\n\t].join('\n');\n\n\tconst systemPrompt = [\n\t\t'You are a helpful assistant that can interact multiple times with a computer shell to solve programming tasks.',\n\t\t'Your response must contain exactly ONE bash code block with ONE command (or commands connected with && or ||).',\n\t\t'',\n\t\t'Format your response as shown in <format_example>.',\n\t\t'',\n\t\t'<format_example>',\n\t\t'```bash',\n\t\t'your_command_here',\n\t\t'```',\n\t\t'</format_example>',\n\t\t'',\n\t\t'Failure to follow these rules will cause your response to be rejected.',\n\t\t'',\n\t\t'=== EDIT COMMAND FORMAT (IMPORTANT) ===',\n\t\t'When you want to EDIT a file, you MUST encode the edit using line-based sed commands in ONE of the following forms,',\n\t\t'and you MUST NOT use substitution commands like ""Ns/old/new/g"".',\n\t\t'',\n\t\t'Assume all line numbers are 1-based and paths are absolute.',\n\t\t'Allowed edit encodings (choose exactly one per response):',\n\t\t'',\n\t\t'1) Replace a contiguous block of lines:',\n\t\t"" sed -i 'START,ENDc\\"",\n\t\t'NEW_LINE_1',\n\t\t'NEW_LINE_2',\n\t\t""..."",\n\t\t""' /abs/path/to/file && cat -n /abs/path/to/file | sed -n 'VSTART,VENDp'"",\n\t\t'',\n\t\t'2) Delete a contiguous block of lines:',\n\t\t"" sed -i 'START,ENDd' /abs/path/to/file && cat -n /abs/path/to/file | sed -n 'VSTART,VENDp'"",\n\t\t'',\n\t\t'3) Insert new lines BEFORE a given line:',\n\t\t"" sed -i 'STARTi\\"",\n\t\t'NEW_LINE_1',\n\t\t'NEW_LINE_2',\n\t\t""..."",\n\t\t""' /abs/path/to/file && cat -n /abs/path/to/file | sed -n 'VSTART,VENDp'"",\n\t\t'',\n\t\t'4) Append new lines at the END of the file:',\n\t\t"" sed -i '$a\\"",\n\t\t'NEW_LINE_1',\n\t\t'NEW_LINE_2',\n\t\t""..."",\n\t\t""' /abs/path/to/file && cat -n /abs/path/to/file | sed -n 'VSTART,VENDp'"",\n\t\t'',\n\t\t'Where VSTART and VEND specify a small viewport around the edited region.',\n\t\t'',\n\t\t'Do NOT emit commands like ""3s/print/print()/g"" or any other ""s/old/new/"" style sed substitution; instead,',\n\t\t'always rewrite the affected lines using one of the line-based forms above.',\n\t\t'',\n\t\t'When you are NOT editing files (e.g., running tests, git commands, tools, etc.), you may emit arbitrary bash commands.'\n\t].join('\n');\n\n\tconst conversationMessages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }> = [\n\t\t{ role: 'system', content: systemPrompt },\n\t\t{ role: 'assistant', content: fencedBashBlock(metadataCommand) },\n\t\t{ role: 'user', content: formatStdoutBlock(metadataSummary) },\n\t\t{ role: 'assistant', content: fencedBashBlock(`cat -n ${filePath}`) },\n\t\t{ role: 'user', content: formatStdoutBlock(formatLineNumberedOutput(fullText)) }\n\t];\n\n\tif (viewport.end >= viewport.start) {\n\t\tconst viewportOutput = formatLineNumberedOutput(fullText, viewport.start, viewport.end);\n\t\tconversationMessages.push(\n\t\t\t{ role: 'assistant', content: fencedBashBlock(`cat -n ${filePath} | sed -n '${viewport.start},${viewport.end}p'`) },\n\t\t\t{ role: 'user', content: formatStdoutBlock(viewportOutput) }\n\t\t);\n\t}\n\n\tconst requestBody: any = {\n\t\tmodel: modelName,\n\t\tmessages: conversationMessages\n\t};\n\tif (!USE_GEMINI) {\n\t\trequestBody.temperature = 0.7;\n\t\trequestBody.top_p = 0.8;\n\t\trequestBody.top_k = 20;\n\t\trequestBody.min_p = 0;\n\t\trequestBody.extra_body = {\n\t\t\tchat_template_kwargs: {\n\t\t\t\tenable_thinking: false\n\t\t\t}\n\t\t};\n\t}\n\n\tconst postData = JSON.stringify(requestBody);\n\theaders['Content-Length'] = Buffer.byteLength(postData);\n\n\tconst options: any = {\n\t\thostname,\n\t\tport,\n\t\tpath,\n\t\tmethod: 'POST',\n\t\theaders\n\t};\n\tif (signal) {\n\t\toptions.signal = signal;\n\t}\n\n\tconst requestModule = useHttps ? https : http;\n\n\tconst json = await new Promise<any>((resolve, reject) => {\n\t\tconst req = requestModule.request(options, (res: http.IncomingMessage) => {\n\t\t\tlet data = '';\n\t\t\tres.on('data', (chunk: Buffer) => { data += chunk.toString(); });\n\t\t\tres.on('end', () => {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(JSON.parse(data));\n\t\t\t\t} catch (err) {\n\t\t\t\t\treject(new Error(`Failed to parse response: ${err instanceof Error ? err.message : String(err)}`));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\treq.on('error', (err: Error) => reject(err));\n\t\treq.write(postData);\n\t\treq.end();\n\t});\n\n\tconst content = extractChatContent(json);\n\tif (typeof content !== 'string' || content.trim().length === 0) {\n\t\tthrow new Error('Empty model content');\n\t}\n\tconst action = parsePlannedAction(content, doc);\n\tif (!action) {\n\t\tthrow new Error('No valid action parsed from model output');\n\t}\n\treturn action;\n}\n\nfunction extractChatContent(json: any): string | undefined {\n\ttry {\n\t\tif (json && Array.isArray(json.choices) && json.choices[0]) {\n\t\t\tconst choice = json.choices[0];\n\t\t\tif (choice.message && typeof choice.message.content === 'string') {\n\t\t\t\treturn choice.message.content;\n\t\t\t}\n\t\t\tif (typeof choice.text === 'string') {\n\t\t\t\treturn choice.text;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction parsePlannedAction(raw: string, doc?: vscode.TextDocument): PlannedAction | undefined {\n\tconst command = extractBashCommand(raw);\n\tif (!command) {\n\t\treturn undefined;\n\t}\n\tconst normalized = command.replace(/<think>[\s\S]*?<\/think>/gi, '').trim();\n\tif (!normalized) {\n\t\treturn undefined;\n\t}\n\t// Try to interpret the command as a structured VS Code action derived from the bash transcript.\n\tif (doc) {\n\t\t// 1) Edits encoded as sed -i ... (insert/replace/delete)\n\t\tconst editAction = parseEditFromSedCommand(normalized, doc);\n\t\tif (editAction) {\n\t\t\treturn editAction;\n\t\t}\n\t\t// 2) Viewport / selection moves encoded as cat -n ... | sed -n 'vstart,vendp'\n\t\tconst viewportAction = parseViewportFromCatCommand(normalized, doc);\n\t\tif (viewportAction) {\n\t\t\treturn viewportAction;\n\t\t}\n\t}\n\t// Fallback: execute the raw command in the integrated terminal.\n\treturn { kind: 'terminalSendText', text: normalized };\n}\n\n/**\n * Parse a sed-based edit command of the form emitted by the NeMo serializer into a VS Code edit action.\n *\n * Supported patterns (1-based line numbers, mirroring serialization_utils.py):\n * sed -i 'START,ENDc\n<replacement...>' <file> -> editReplace\n * sed -i 'START,ENDd' <file> -> editDelete\n * sed -i 'STARTi\n<insert...>' <file> -> editInsert (before START)\n * sed -i '$a\n<append...>' <file> -> editInsert (append at EOF)\n *\n * If the command does not match these patterns, returns undefined.\n */\nfunction parseEditFromSedCommand(command: string, doc: vscode.TextDocument): PlannedAction | undefined {\n\t// Only consider the first command before && / ||, since cat -n etc. are for viewport only.\n\tconst main = command.split(/&&|\|\|/)[0]?.trim() ?? '';\n\tif (!main) {\n\t\treturn undefined;\n\t}\n\n\t// Match: sed -i '<script>' <file>\n\tconst sedMatch = main.match(/sed\s+-i\s+'([\s\S]*?)'\s+([^\s&|]+)\s*$/);\n\tif (!sedMatch) {\n\t\treturn undefined;\n\t}\n\tconst script = sedMatch[1] ?? '';\n\tconst targetFile = sedMatch[2] ?? '';\n\tconst activePath = doc.uri.fsPath;\n\t// Be conservative: only apply edits when the sed target matches the active document path.\n\tif (targetFile !== activePath) {\n\t\treturn undefined;\n\t}\n\n\t// Delete: ""START,ENDd""\n\tconst deleteMatch = script.match(/^(\d+),(\d+)d$/);\n\tif (deleteMatch) {\n\t\tconst startLine1 = Number(deleteMatch[1]);\n\t\tconst endLine1 = Number(deleteMatch[2]);\n\t\tif (!Number.isFinite(startLine1) || !Number.isFinite(endLine1)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst startLine0 = Math.max(0, startLine1 - 1);\n\t\tconst endLine0 = Math.max(0, endLine1 - 1);\n\n\t\tlet endPosLine = endLine0 + 1;\n\t\tlet endPosChar = 0;\n\t\tif (endPosLine >= doc.lineCount) {\n\t\t\tendPosLine = doc.lineCount - 1;\n\t\t\tendPosChar = doc.lineAt(endPosLine).range.end.character;\n\t\t}\n\t\treturn {\n\t\t\tkind: 'editDelete',\n\t\t\trange: {\n\t\t\t\tstart: [startLine0, 0],\n\t\t\t\tend: [endPosLine, endPosChar],\n\t\t\t},\n\t\t};\n\t}\n\n\t// Replace: ""START,ENDc\newline<payload...>""\n\tconst replaceMatch = script.match(/^(\d+),(\d+)c\\\n([\s\S]*)$/);\n\tif (replaceMatch) {\n\t\tconst startLine1 = Number(replaceMatch[1]);\n\t\tconst endLine1 = Number(replaceMatch[2]);\n\t\tlet payload = replaceMatch[3] ?? '';\n\t\tif (!Number.isFinite(startLine1) || !Number.isFinite(endLine1)) {\n\t\t\treturn undefined;\n\t\t}\n\t\t// Unescape single quotes as done in _escape_single_quotes_for_sed.\n\t\tpayload = payload.replace(/'\""'\""'/g, ""'"");\n\t\tconst startLine0 = Math.max(0, startLine1 - 1);\n\t\tconst endLine0 = Math.max(0, endLine1 - 1);\n\t\tconst startPos: [number, number] = [startLine0, 0];\n\n\t\t// Replace up to the start of the line after endLine, or end-of-document.\n\t\tlet endPosLine = endLine0 + 1;\n\t\tlet endPosChar = 0;\n\t\tif (endPosLine >= doc.lineCount) {\n\t\t\tendPosLine = doc.lineCount - 1;\n\t\t\tendPosChar = doc.lineAt(endPosLine).range.end.character;\n\t\t}\n\n\t\t// Preserve multi-line payload as-is; append a trailing newline so sed-style replacements map naturally.\n\t\tconst text = payload.endsWith('\n') ? payload : payload + '\n';\n\t\treturn {\n\t\t\tkind: 'editReplace',\n\t\t\trange: { start: startPos, end: [endPosLine, endPosChar] },\n\t\t\ttext,\n\t\t};\n\t}\n\n\t// Insert before a given line: ""STARTi\newline<payload...>""\n\tconst insertMatch = script.match(/^(\d+)i\\\n([\s\S]*)$/);\n\tif (insertMatch) {\n\t\tconst line1 = Number(insertMatch[1]);\n\t\tlet payload = insertMatch[2] ?? '';\n\t\tif (!Number.isFinite(line1)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tpayload = payload.replace(/'\""'\""'/g, ""'"");\n\t\tconst insertLine0 = Math.max(0, line1 - 1);\n\t\tconst position: [number, number] = [insertLine0, 0];\n\t\tconst text = payload.endsWith('\n') ? payload : payload + '\n';\n\t\treturn {\n\t\t\tkind: 'editInsert',\n\t\t\tposition,\n\t\t\ttext,\n\t\t};\n\t}\n\n\t// Append at end of file: ""$a\newline<payload...>""\n\tconst appendMatch = script.match(/^\$a\\\n([\s\S]*)$/);\n\tif (appendMatch) {\n\t\tlet payload = appendMatch[1] ?? '';\n\t\tpayload = payload.replace(/'\""'\""'/g, ""'"");\n\t\tconst insertLine0 = doc.lineCount;\n\t\tconst position: [number, number] = [insertLine0, 0];\n\t\tconst needsLeadingNewline = doc.lineCount > 0;\n\t\tconst base = payload.endsWith('\n') ? payload : payload + '\n';\n\t\tconst text = needsLeadingNewline ? '\n' + base : base;\n\t\treturn {\n\t\t\tkind: 'editInsert',\n\t\t\tposition,\n\t\t\ttext,\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Parse viewport / selection commands of the form:\n * cat -n <file> | sed -n 'START,ENDp'\n *\n * into a lightweight VS Code selection move (setSelections). This mirrors how\n * selection and viewport events are serialized in serialization_utils.py.\n */\nfunction parseViewportFromCatCommand(command: string, doc: vscode.TextDocument): PlannedAction | undefined {\n\tconst main = command.split(/&&|\|\|/)[0]?.trim() ?? '';\n\tif (!main) {\n\t\treturn undefined;\n\t}\n\n\t// Simple file-open: cat -n <file>\n\tconst simpleCatMatch = main.match(/^cat\s+-n\s+([^\s|]+)\s*$/);\n\tif (simpleCatMatch) {\n\t\tconst targetFile = simpleCatMatch[1] ?? '';\n\t\tif (targetFile !== doc.uri.fsPath) {\n\t\t\treturn undefined;\n\t\t}\n\t\t// Ensure the active document is visible; rely on existing editor to handle this.\n\t\treturn { kind: 'showTextDocument' };\n\t}\n\n\t// Viewport slice: cat -n <file> | sed -n 'START,ENDp'\n\tconst viewportMatch = main.match(/^cat\s+-n\s+([^\s|]+)\s*\|\s*sed\s+-n\s+'(\d+),(\d+)p'\s*$/);\n\tif (!viewportMatch) {\n\t\treturn undefined;\n\t}\n\n\tconst targetFile = viewportMatch[1] ?? '';\n\tconst startStr = viewportMatch[2] ?? '';\n\tconst endStr = viewportMatch[3] ?? '';\n\n\tif (targetFile !== doc.uri.fsPath) {\n\t\treturn undefined;\n\t}\n\n\tconst startLine1 = Number(startStr);\n\tconst endLine1 = Number(endStr);\n\tif (!Number.isFinite(startLine1) || !Number.isFinite(endLine1)) {\n\t\treturn undefined;\n\t}\n\n\t// Place the cursor in the middle of the viewport (1-based to 0-based).\n\tconst center1 = Math.floor((startLine1 + endLine1) / 2);\n\tconst center0 = Math.max(0, center1 - 1);\n\tconst lastLine = Math.max(0, doc.lineCount - 1);\n\tconst line = Math.min(center0, lastLine);\n\tconst endChar = doc.lineAt(line).range.end.character;\n\n\treturn {\n\t\tkind: 'setSelections',\n\t\tselections: [\n\t\t\t{\n\t\t\t\tstart: [line, endChar],\n\t\t\t\tend: [line, endChar],\n\t\t\t},\n\t\t],\n\t};\n}\n\nfunction extractBashCommand(raw: string): string | undefined {\n\tif (!raw) {\n\t\treturn undefined;\n\t}\n\tconst trimmed = raw.trim();\n\tconst fenceMatch = trimmed.match(/```(?:bash)?\s*([\s\S]*?)```/i);\n\tif (fenceMatch && fenceMatch[1]) {\n\t\treturn fenceMatch[1];\n\t}\n\t// Fallback: treat entire response as the command\n\treturn trimmed.length > 0 ? trimmed : undefined;\n}",typescript,tab
|
| 3 |
+
2,219,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"6:49:46 PM [info] Activating crowd-code\n6:49:46 PM [info] Recording started\n6:49:46 PM [info] Initializing git provider using file system watchers...\n6:49:46 PM [info] Git repository found\n6:49:46 PM [info] Git provider initialized successfully\n6:49:46 PM [info] Initial git state: [object Object]\n",Log,tab
|
| 4 |
+
3,355,"TERMINAL",0,0,"",,terminal_focus
|
| 5 |
+
4,356,"TERMINAL",0,0,"",,terminal_focus
|
| 6 |
+
5,1124,"src/extension.ts",0,0,"",typescript,tab
|
| 7 |
+
6,88659,"src/extension.ts",0,0,"",typescript,tab
|
| 8 |
+
7,88662,"src/extension.ts",131,0,"",typescript,selection_command
|
| 9 |
+
8,96354,"src/extension.ts",0,0,"import * as vscode from 'vscode';\nimport * as https from 'https';\nimport * as http from 'http';\nimport { Buffer } from 'buffer';\n\n\nconst SGLANG_HOSTNAME = 'hai007';\nconst SGLANG_PORT = 30000;\nconst SGLANG_BASE_PATH = '/v1/chat/completions';\nconst SGLANG_MODEL_NAME = 'qwen/qwen3-0.6b';\n\nconst GEMINI_HOSTNAME = 'generativelanguage.googleapis.com';\nconst GEMINI_PORT = 443;\nconst GEMINI_BASE_PATH = '/v1beta/openai/chat/completions';\nconst GEMINI_MODEL_NAME = 'gemini-2.5-flash';\n\nconst USE_GEMINI = false;\n\nexport function activate(context: vscode.ExtensionContext) {\n\n\tconsole.log('[crowd-pilot] Extension activated');\n\n\t// Configure terminal to allow tab keybinding to work\n\t(async () => {\n\t\tconst config = vscode.workspace.getConfiguration('terminal.integrated');\n\t\tconst commandsToSkipShell = config.get<string[]>('commandsToSkipShell', []);\n\t\tlet updated = false;\n\t\tif (!commandsToSkipShell.includes('crowd-pilot.modelRun')) {\n\t\t\tcommandsToSkipShell.push('crowd-pilot.modelRun');\n\t\t\tupdated = true;\n\t\t}\n\t\tif (!commandsToSkipShell.includes('crowd-pilot.hideUi')) {\n\t\t\tcommandsToSkipShell.push('crowd-pilot.hideUi');\n\t\t\tupdated = true;\n\t\t}\n\t\tif (updated) {\n\t\t\tawait config.update('commandsToSkipShell', commandsToSkipShell, vscode.ConfigurationTarget.Global);\n\t\t}\n\t})().catch((err) => console.error('[crowd-pilot] Startup initialization error:', err));\n\n\tconst hideUi = vscode.commands.registerCommand('crowd-pilot.hideUi', () => {\n\t\thidePreviewUI(true);\n\t});\n\n\tconst modelRun = vscode.commands.registerCommand('crowd-pilot.modelRun', async () => {\n\t\tconst editor = vscode.window.activeTextEditor;\n\t\tif (!editor) {\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\t// Confirm only when a suggestion is visible\n\t\t\tif (!previewVisible) { return; }\n\t\t\tlet action: PlannedAction | undefined = currentAction;\n\t\t\tif (!action) {\n\t\t\t\tconst single = await requestModelActions(editor);\n\t\t\t\tcurrentAction = single;\n\t\t\t\taction = single;\n\t\t\t}\n\t\t\tif (!action) {\n\t\t\t\thidePreviewUI();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\thidePreviewUI(false);\n\t\t\tawait executeAction(action);\n\t\t\tautoShowNextAction();\n\t\t} catch (err) {\n\t\t\tconst errorMessage = err instanceof Error ? err.message : String(err);\n\t\t\tvscode.window.showErrorMessage(`Model run failed: ${errorMessage}`);\n\t\t}\n\t});\n\n\tconst sglangTest = vscode.commands.registerCommand('crowd-pilot.sglangTest', async () => {\n\t\ttry {\n\t\t\tawait callSGLangChat();\n\t\t} catch (err) {\n\t\t\tconst errorMessage = err instanceof Error ? err.message : String(err);\n\t\t\tvscode.window.showErrorMessage(`SGLang test failed: ${errorMessage}`);\n\t\t}\n\t});\n\n\t// Auto-preview listeners\n\tconst debouncedAutoPreview = debounce(() => {\n\t\tautoShowNextAction();\n\t}, 250);\n\tconst onSelChange = vscode.window.onDidChangeTextEditorSelection((e) => {\n\t\tif (e.textEditor === vscode.window.activeTextEditor) {\n\t\t\tsuppressAutoPreview = false;\n\t\t\tdebouncedAutoPreview();\n\t\t}\n\t});\n\tconst onActiveChange = vscode.window.onDidChangeActiveTextEditor(() => {\n\t\tsuppressAutoPreview = false;\n\t\tdebouncedAutoPreview();\n\t});\n\tconst onDocChange = vscode.workspace.onDidChangeTextDocument((e) => {\n\t\tif (vscode.window.activeTextEditor?.document === e.document) {\n\t\t\tsuppressAutoPreview = false;\n\t\t\tdebouncedAutoPreview();\n\t\t}\n\t});\n\n\tcontext.subscriptions.push(hideUi, sglangTest, modelRun, onSelChange, onActiveChange, onDocChange);\n}\n\nexport function deactivate() {}\n\n// -------------------- Plan Types & Execution --------------------\ntype PlannedAction =\n| { kind: 'showTextDocument' }\n| { kind: 'setSelections', selections: Array<{ start: [number, number], end: [number, number] }> }\n| { kind: 'editInsert', position: [number, number], text: string }\n| { kind: 'editDelete', range: { start: [number, number], end: [number, number] } }\n| { kind: 'editReplace', range: { start: [number, number], end: [number, number] }, text: string }\n| { kind: 'terminalShow' }\n| { kind: 'terminalSendText', text: string };\n\nlet currentAction: PlannedAction | undefined;\n\nasync function executeAction(action: PlannedAction): Promise<void> {\n\tconst editor = vscode.window.activeTextEditor;\n\tif (!editor) { return; }\n\tconst doc = editor.document;\n\tconst term = vscode.window.terminals[0] ?? vscode.window.createTerminal('Test');\n\tif (action.kind === 'showTextDocument') {\n\t\tawait vscode.window.showTextDocument(doc);\n\t\treturn;\n\t}\n\tif (action.kind === 'setSelections') {\n\t\teditor.selections = action.selections.map(s => new vscode.Selection(\n\t\t\tnew vscode.Position(s.start[0], s.start[1]),\n\t\t\tnew vscode.Position(s.end[0], s.end[1])\n\t\t));\n\t\tif (editor.selections.length > 0) {\n\t\t\teditor.revealRange(editor.selections[0], vscode.TextEditorRevealType.InCenterIfOutsideViewport);\n\t\t}\n\t\treturn;\n\t}\n\tif (action.kind === 'editInsert') {\n\t\tawait editor.edit((e: vscode.TextEditorEdit) => e.insert(new vscode.Position(action.position[0], action.position[1]), action.text));\n\t\treturn;\n\t}\n\tif (action.kind === 'editDelete') {\n\t\tconst range = new vscode.Range(\n\t\t\tnew vscode.Position(action.range.start[0], action.range.start[1]),\n\t\t\tnew vscode.Position(action.range.end[0], action.range.end[1])\n\t\t);\n\t\tawait editor.edit((e: vscode.TextEditorEdit) => e.delete(range));\n\t\treturn;\n\t}\n\tif (action.kind === 'editReplace') {\n\t\tconst range = new vscode.Range(\n\t\t\tnew vscode.Position(action.range.start[0], action.range.start[1]),\n\t\t\tnew vscode.Position(action.range.end[0], action.range.end[1])\n\t\t);\n\t\tawait editor.edit((e: vscode.TextEditorEdit) => e.replace(range, action.text));\n\t\treturn;\n\t}\n\tif (action.kind === 'terminalShow') {\n\t\tterm.show();\n\t\treturn;\n\t}\n\tif (action.kind === 'terminalSendText') {\n\t\tterm.sendText(action.text);\n\t\treturn;\n\t}\n}\n\n// -------------------- UI State & Helpers --------------------\nconst UI_CONTEXT_KEY = 'crowdPilot.uiVisible';\nlet previewVisible = false;\nlet decorationDeleteType: vscode.TextEditorDecorationType | undefined;\nlet decorationReplaceType: vscode.TextEditorDecorationType | undefined;\nlet decorationReplaceBlockType: vscode.TextEditorDecorationType | undefined;\nlet mockStep = 0;\nlet suppressAutoPreview = false;\nlet latestRequestId = 0;\nlet currentAbortController: AbortController | undefined;\n\nfunction disposePreviewDecorations() {\n\ttry { decorationDeleteType?.dispose(); } catch {}\n\ttry { decorationReplaceType?.dispose(); } catch {}\n\ttry { decorationReplaceBlockType?.dispose(); } catch {}\n\tdecorationDeleteType = undefined;\n\tdecorationReplaceType = undefined;\n\tdecorationReplaceBlockType = undefined;\n}\n\nfunction debounce<T extends (...args: any[]) => void>(fn: T, waitMs: number) {\n\tlet timer: NodeJS.Timeout | undefined;\n\treturn (...args: Parameters<T>) => {\n\t\tif (timer) { clearTimeout(timer); }\n\t\ttimer = setTimeout(() => fn(...args), waitMs);\n\t};\n}\n\nfunction getDynamicMargin(editor: vscode.TextEditor, anchorLine: number, text: string): string {\n\t// Count lines in the preview text\n\tconst lines = text.split(/\r?\n/);\n\tconst height = lines.length;\n\t\n\t// We need to check the document lines that will be covered by this panel.\n\t// The panel starts at 'anchorLine' and extends downwards by 'height' lines.\n\t// However, visually, since it's 'after', it sits to the right of 'anchorLine',\n\t// and then flows down.\n\t// So we check document lines from anchorLine to anchorLine + height - 1.\n\t\n\tconst doc = editor.document;\n\tlet maxLen = 0;\n\tconst startLine = anchorLine;\n\tconst endLine = Math.min(doc.lineCount - 1, anchorLine + height - 1);\n\t\n\tfor (let i = startLine; i <= endLine; i++) {\n\t\tconst lineText = doc.lineAt(i).text;\n\t\t// Simple approximation: assume tabs are 4 spaces if we can't get config easily, \n\t\t// or just treat them as 1 char (which might underestimate). \n\t\t// Better to overestimate: treat tab as 4 chars.\n\t\tconst len = lineText.replace(/\t/g, ' ').length;\n\t\tif (len > maxLen) {\n\t\t\tmaxLen = len;\n\t\t}\n\t}\n\t\n\t// Length of the anchor line itself\n\tconst anchorLineText = doc.lineAt(anchorLine).text;\n\tconst anchorLen = anchorLineText.replace(/\t/g, ' ').length;\n\t\n\t// The offset needed is maxLen - anchorLen.\n\t// If maxLen <= anchorLen, offset is 0 (margin is just base padding).\n\t// If maxLen > anchorLen, we need to push right by (maxLen - anchorLen).\n\t\n\tconst diff = Math.max(0, maxLen - anchorLen);\n\t// Base margin 2rem is roughly 4ch. Let's use ch units for everything to be consistent.\n\t// 1ch is width of '0'. In monospace, mostly consistent.\n\t// Add 3ch extra padding for safety/visual gap.\n\tconst margin = diff + 4; \n\treturn `${margin}ch`;\n}\n\nfunction showPreviewUI(action: PlannedAction): void {\n\tconst editor = vscode.window.activeTextEditor;\n\tif (!editor) { return; }\n\tdisposePreviewDecorations();\n\n\t// FIXME (f.srambical): add file switch \n\tconst next = (action.kind === 'editInsert' || action.kind === 'editDelete' || action.kind === 'editReplace' || action.kind === 'terminalSendText' || action.kind === 'setSelections') ? action : undefined;\n\tif (!next) {\n\t\tpreviewVisible = false;\n\t\tvscode.commands.executeCommand('setContext', UI_CONTEXT_KEY, false);\n\t\tcurrentAction = action;\n\t\treturn;\n\t}\n\n\tconst trimText = (t: string) => {\n\t\tconst oneLine = t.replace(/\r?\n/g, '\\n');\n\t\treturn oneLine.length > 80 ? oneLine.slice(0, 77) + '…' : oneLine;\n\t};\n\n\tif (next.kind === 'setSelections') {\n\t\t// For setSelections, we only preview the primary selection's start/active position\n\t\tconst selection = next.selections[0];\n\t\tconst targetPos = new vscode.Position(selection.start[0], selection.start[1]);\n\t\t// Check if the target position is visible\n\t\tconst isVisible = editor.visibleRanges.some(r => r.contains(targetPos));\n\t\t\n\t\tlet anchorPos = targetPos;\n\t\tlet label = ""↳ Move Cursor Here"";\n\n\t\tif (!isVisible && editor.visibleRanges.length > 0) {\n\t\t\tconst firstVisible = editor.visibleRanges[0].start;\n\t\t\tconst lastVisible = editor.visibleRanges[editor.visibleRanges.length - 1].end;\n\t\t\t\n\t\t\tif (targetPos.isBefore(firstVisible)) {\n\t\t\t\tanchorPos = editor.document.lineAt(firstVisible.line).range.end;\n\t\t\t} else {\n\t\t\t\tanchorPos = editor.document.lineAt(lastVisible.line).range.end;\n\t\t\t}\n\n\t\t\tif (targetPos.line < anchorPos.line) {\n\t\t\t\tlabel = `↑ Move Cursor to Line ${targetPos.line + 1}`;\n\t\t\t} else {\n\t\t\t\tlabel = `↓ Move Cursor to Line ${targetPos.line + 1}`;\n\t\t\t}\n\t\t}\n\n\t\tconst margin = getDynamicMargin(editor, anchorPos.line, label);\n\n\t\tdecorationReplaceBlockType = vscode.window.createTextEditorDecorationType({\n\t\t\tafter: {\n\t\t\t\tcontentText: '',\n\t\t\t\tcolor: new vscode.ThemeColor('charts.purple'),\n\t\t\t\tbackgroundColor: new vscode.ThemeColor('editor.background'),\n\t\t\t\tfontStyle: 'italic',\n\t\t\t\tfontWeight: '600',\n\t\t\t\tmargin: `0 0 0 ${margin}`,\n\t\t\t\ttextDecoration: `none; display: inline-block; white-space: pre; content: ""${label}""; border: 1px solid var(--vscode-charts-purple); padding: 4px; border-radius: 4px; box-shadow: 0 4px 8px rgba(0,0,0,0.25); pointer-events: none; position: relative; z-index: 100; vertical-align: top;`\n\t\t\t}\n\t\t});\n\t\teditor.setDecorations(decorationReplaceBlockType, [{ range: new vscode.Range(anchorPos, anchorPos) }]);\n\t} else if (next.kind === 'terminalSendText') {\n\t\tconst cursor = editor.selection.active;\n\t\tconst lineEnd = editor.document.lineAt(cursor.line).range.end;\n\t\tconst summary = trimText(next.text || '');\n\t\tconst label = `↳ Execute shell command in terminal: ${summary}`;\n\t\tconst margin = getDynamicMargin(editor, cursor.line, label);\n\n\t\tdecorationReplaceBlockType = vscode.window.createTextEditorDecorationType({\n\t\t\tafter: {\n\t\t\t\tcontentText: '',\n\t\t\t\tcolor: new vscode.ThemeColor('charts.purple'),\n\t\t\t\tbackgroundColor: new vscode.ThemeColor('editor.background'),\n\t\t\t\tfontStyle: 'italic',\n\t\t\t\tfontWeight: '600',\n\t\t\t\tmargin: `0 0 0 ${margin}`,\n\t\t\t\ttextDecoration: `none; display: inline-block; white-space: pre; content: ""${label.replace(/""/g, '\\""')}""; border: 1px solid var(--vscode-charts-purple); padding: 4px; border-radius: 4px; box-shadow: 0 4px 8px rgba(0,0,0,0.25); pointer-events: none; position: relative; z-index: 100; vertical-align: top;`\n\t\t\t}\n\t\t});\n\t\teditor.setDecorations(decorationReplaceBlockType, [{ range: new vscode.Range(lineEnd, lineEnd) }]);\n\t} else if (next.kind === 'editInsert') {\n\t\tconst posLine = next.position[0];\n\t\tconst fullBlock = next.text;\n\t\tconst cssContent = fullBlock\n\t\t\t.replace(/""/g, '\\""')\n\t\t\t.replace(/\r?\n/g, '\\A ');\n\n\t\tconst docLineCount = editor.document.lineCount;\n\t\t// If inserting at EOF (or beyond), attach to the last line.\n\t\t// Otherwise, attach to the line AT the insertion point and shift visually UP into the gap.\n\t\tlet anchorLine = posLine;\n\t\tlet shiftUp = true;\n\t\t\n\t\tif (anchorLine >= docLineCount) {\n\t\t\tanchorLine = docLineCount - 1;\n\t\t\tshiftUp = false; // At EOF, we just append below or to the right\n\t\t}\n\n\t\tconst anchorPos = new vscode.Position(anchorLine, Number.MAX_VALUE); \n\t\t\n\t\t// We attach to the line AT the insertion point.\n\t\t// The panel floats to the right of this line.\n\t\t// The dashed line connects the start of this line to the panel.\n\t\t// This indicates that the new text will be inserted at this line position (pushing the current line down).\n\t\tconst marginCheckLine = anchorLine;\n\t\tconst margin = getDynamicMargin(editor, marginCheckLine, fullBlock);\n\n\t\tconst topOffset = '0';\n\n\t\t// Dashed line style\n\t\t// We use 'before' decoration for the line.\n\t\t// It needs to be absolute, full width (or enough to reach left), \n\t\t// and aligned with the panel top.\n\t\tconst beforeDecoration = {\n\t\t\tcontentText: '',\n\t\t\ttextDecoration: `none; position: absolute; left: 0; width: 100vw; border-top: 1px dashed var(--vscode-charts-purple); top: 0; height: 0; z-index: 99; pointer-events: none;`\n\t\t};\n\n\t\tdecorationReplaceBlockType = vscode.window.createTextEditorDecorationType({\n\t\t\tbefore: beforeDecoration,\n\t\t\tafter: {\n\t\t\t\tcontentText: '',\n\t\t\t\tcolor: new vscode.ThemeColor('charts.purple'),\n\t\t\t\tbackgroundColor: new vscode.ThemeColor('editor.background'),\n\t\t\t\tfontStyle: 'italic',\n\t\t\t\tfontWeight: '600',\n\t\t\t\tmargin: `0 0 0 ${margin}`,\n\t\t\t\ttextDecoration: `none; display: inline-block; white-space: pre; content: ""${cssContent}""; border: 1px solid var(--vscode-charts-purple); padding: 4px; border-radius: 4px; box-shadow: 0 4px 8px rgba(0,0,0,0.25); pointer-events: none; position: relative; z-index: 100; vertical-align: top; top: ${topOffset};`\n\t\t\t}\n\t\t});\n\t\teditor.setDecorations(decorationReplaceBlockType, [{ range: new vscode.Range(anchorPos, anchorPos) }]);\n\t} else if (next.kind === 'editDelete') {\n\t\tconst range = new vscode.Range(\n\t\t\tnew vscode.Position(next.range.start[0], next.range.start[1]),\n\t\t\tnew vscode.Position(next.range.end[0], next.range.end[1])\n\t\t);\n\t\tdecorationDeleteType = vscode.window.createTextEditorDecorationType({\n\t\t\tbackgroundColor: 'rgba(255, 60, 60, 0.18)',\n\t\t\tborder: '1px solid rgba(255, 60, 60, 0.35)',\n\t\t\ttextDecoration: 'line-through'\n\t\t});\n\t\teditor.setDecorations(decorationDeleteType, [{ range }]);\n\t} else if (next.kind === 'editReplace') {\n\t\tconst range = new vscode.Range(\n\t\t\tnew vscode.Position(next.range.start[0], next.range.start[1]),\n\t\t\tnew vscode.Position(next.range.end[0], next.range.end[1])\n\t\t);\n\t\t// Highlight original range (to be replaced)\n\t\tdecorationReplaceType = vscode.window.createTextEditorDecorationType({\n\t\t\tbackgroundColor: 'rgba(255,165,0,0.15)',\n\t\t\tborder: '1px dashed rgba(255,165,0,0.45)',\n\t\t\tcolor: new vscode.ThemeColor('disabledForeground'),\n\t\t\ttextDecoration: 'line-through'\n\t\t});\n\t\teditor.setDecorations(decorationReplaceType, [{ range }]);\n\n\t\t// Show replacement block to the right of the first replaced line\n\t\tconst fullBlock = next.text;\n\t\t\n\t\t// CSS-escape the text for the 'content' property:\n\t\t// - Escape double quotes\n\t\t// - Replace newlines with \A (CSS newline)\n\t\tconst cssContent = fullBlock\n\t\t\t.replace(/""/g, '\\""')\n\t\t\t.replace(/\r?\n/g, '\\A '); \n\n\t\t// Attach 'after' decoration to the start of the replacement range\n\t\t// (Actually, attaching to the end of the first line is safer for 'after')\n\t\tconst anchorLine = range.start.line;\n\t\tconst anchorPos = new vscode.Position(anchorLine, Number.MAX_VALUE);\n\t\tconst margin = getDynamicMargin(editor, anchorLine, fullBlock);\n\n\t\tdecorationReplaceBlockType = vscode.window.createTextEditorDecorationType({\n\t\t\tafter: {\n\t\t\t\tcontentText: '', // Handled by CSS content\n\t\t\t\tcolor: new vscode.ThemeColor('charts.purple'),\n\t\t\t\tbackgroundColor: new vscode.ThemeColor('editor.background'),\n\t\t\t\tfontStyle: 'italic',\n\t\t\t\tfontWeight: '600',\n\t\t\t\tmargin: `0 0 0 ${margin}`,\n\t\t\t\ttextDecoration: `none; display: inline-block; white-space: pre; content: ""${cssContent}""; border: 1px solid var(--vscode-charts-purple); padding: 4px; border-radius: 4px; box-shadow: 0 4px 8px rgba(0,0,0,0.25); pointer-events: none; position: relative; z-index: 100; vertical-align: top;`\n\t\t\t}\n\t\t});\n\t\teditor.setDecorations(decorationReplaceBlockType, [{ range: new vscode.Range(anchorPos, anchorPos) }]);\n\t}\n\n\tpreviewVisible = true;\n\tvscode.commands.executeCommand('setContext', UI_CONTEXT_KEY, true);\n\tcurrentAction = action;\n}\n\nfunction hidePreviewUI(suppress?: boolean): void {\n\tdisposePreviewDecorations();\n\tpreviewVisible = false;\n\tvscode.commands.executeCommand('setContext', UI_CONTEXT_KEY, false);\n\tif (suppress) {\n\t\tsuppressAutoPreview = true;\n\t}\n}\n\n// -------------------- Hardcoded single-step actions --------------------\nfunction getHardcodedNextAction(editor: vscode.TextEditor): PlannedAction | undefined {\n\tconst cursor = editor.selection.active;\n\tconst doc = editor.document;\n\tconst lineCount = doc.lineCount;\n\tconst clamp = (n: number, min: number, max: number) => Math.max(min, Math.min(max, n));\n\n\t// Step 0: Insert multiline content two lines below the cursor (start of target line)\n\tif (mockStep === 0) {\n\t\tconst targetLine = clamp(cursor.line + 2, 0, Math.max(0, lineCount - 1));\n\t\treturn {\n\t\t\tkind: 'editInsert',\n\t\t\tposition: [targetLine, 0],\n\t\t\ttext: '/* crowd-pilot: insert start */\nline A\nline B\n/* crowd-pilot: insert end */\n'\n\t\t};\n\t}\n\t// Step 1: Replace a two-line range three and four lines below the cursor\n\tif (mockStep === 1) {\n\t\tconst startLine = clamp(cursor.line + 3, 0, Math.max(0, lineCount - 1));\n\t\tconst endLine = clamp(startLine + 1, 0, Math.max(0, lineCount - 1));\n\t\tconst endChar = doc.lineAt(endLine).range.end.character;\n\t\tconst range = {\n\t\t\tstart: [startLine, 0] as [number, number],\n\t\t\tend: [endLine, endChar] as [number, number]\n\t\t};\n\t\tconst replacement = [\n\t\t\t'/* crowd-pilot: replacement */',\n\t\t\t'REPLACED LINE 1',\n\t\t\t'REPLACED LINE 2'\n\t\t].join('\n');\n\t\treturn { kind: 'editReplace', range, text: replacement };\n\t}\n\t// Step 2: Delete a three-line range six to eight lines below the cursor\n\tif (mockStep === 2) {\n\t\tconst startLine = clamp(cursor.line + 6, 0, Math.max(0, lineCount - 1));\n\t\tconst endLine = clamp(startLine + 2, 0, Math.max(0, lineCount - 1));\n\t\t\n\t\t// To fully delete the lines including the newline, we target the start of the next line.\n\t\tlet endPosLine = endLine + 1;\n\t\tlet endPosChar = 0;\n\t\t\n\t\tif (endPosLine >= lineCount) {\n\t\t\t// If deleting the last line(s), just go to the end of the document\n\t\t\tendPosLine = lineCount - 1;\n\t\t\tendPosChar = doc.lineAt(endPosLine).range.end.character;\n\t\t}\n\n\t\tconst range = {\n\t\t\tstart: [startLine, 0] as [number, number],\n\t\t\tend: [endPosLine, endPosChar] as [number, number]\n\t\t};\n\t\treturn { kind: 'editDelete', range };\n\t}\n\t// Step 3: Execute in Terminal\n\tif (mockStep === 3) {\n\t\treturn { kind: 'terminalSendText', text: 'echo ""Hello World""' };\n\t}\n\t// Step 4: Move Cursor to End of File\n\tif (mockStep === 4) {\n\t\tconst lastLine = doc.lineCount - 1;\n\t\tconst lastChar = doc.lineAt(lastLine).range.end.character;\n\t\treturn {\n\t\t\tkind: 'setSelections',\n\t\t\tselections: [{ start: [lastLine, lastChar], end: [lastLine, lastChar] }]\n\t\t};\n\t}\n\treturn undefined;\n}\n\nfunction advanceMockStep(): void {\n\tmockStep = (mockStep + 1) % 5;\n}\n\nasync function autoShowNextAction(): Promise<void> {\n\tif (suppressAutoPreview) { return; }\n\tconst editor = vscode.window.activeTextEditor;\n\tif (!editor) { return; }\n\ttry {\n\t\tcurrentAbortController?.abort();\n\t\tconst controller = new AbortController();\n\t\tcurrentAbortController = controller;\n\t\tconst requestId = ++latestRequestId;\n\t\tconst next = await requestModelActions(editor, controller.signal);\n\t\tif (requestId !== latestRequestId) { return; }\n\t\tif (next) { showPreviewUI(next); } else { hidePreviewUI(); }\n\t} catch (err) {\n\t\tconst e = err as any;\n\t\tconst isAbort = e?.name === 'AbortError' || /aborted/i.test(String(e?.message ?? ''));\n\t\tif (isAbort) { return; }\n\t\thidePreviewUI();\n\t}\n}\n\n// -------------------- SGLang Client (simple test) --------------------\nasync function callSGLangChat(): Promise<void> {\n\tconst config = vscode.workspace.getConfiguration();\n\t\n\tlet hostname: string;\n\tlet port: number;\n\tlet path: string;\n\tlet useHttps = true;\n\tlet modelName: string;\n\tconst headers: any = {\n\t\t'Content-Type': 'application/json'\n\t};\n\n\tif (!USE_GEMINI) {\n\t\t// SGLang\n\t\thostname = SGLANG_HOSTNAME;\n\t\tport = SGLANG_PORT;\n\t\tpath = SGLANG_BASE_PATH;\n\t\tuseHttps = false; \n\t\tmodelName = SGLANG_MODEL_NAME;\n\t} else {\n\t\t// Gemini\n\t\tconst apiKey = config.get<string>('crowd-pilot.apiKey');\n\t\tif (!apiKey) {\n\t\t\tvscode.window.showErrorMessage('Crowd Pilot: Please set your API Key in settings (crowd-pilot.apiKey).');\n\t\t\treturn;\n\t\t}\n\t\thostname = GEMINI_HOSTNAME;\n\t\tport = GEMINI_PORT;\n\t\tpath = GEMINI_BASE_PATH;\n\t\theaders['Authorization'] = `Bearer ${apiKey}`;\n\t\tmodelName = GEMINI_MODEL_NAME;\n\t}\n\n\tconst requestBody: any = {\n\t\tmodel: modelName,\n\t\tmessages: [\n\t\t\t{ role: 'user', content: 'What is the capital of France?' }\n\t\t]\n\t};\n\tif (!USE_GEMINI) {\n\t\trequestBody.temperature = 0.7;\n\t\trequestBody.top_p = 0.8;\n\t\trequestBody.top_k = 20;\n\t\trequestBody.min_p = 0;\n\t\trequestBody.extra_body = {\n\t\t\tchat_template_kwargs: {\n\t\t\t\tenable_thinking: false\n\t\t\t}\n\t\t};\n\t}\n\tconst postData = JSON.stringify(requestBody);\n\theaders['Content-Length'] = Buffer.byteLength(postData);\n\n\tconst options = {\n\t\thostname,\n\t\tport,\n\t\tpath,\n\t\tmethod: 'POST',\n\t\theaders\n\t};\n\n\tconst requestModule = useHttps ? https : http;\n\n\ttry {\n\t\tconst json = await new Promise<any>((resolve, reject) => {\n\t\t\tconst req = requestModule.request(options, (res: http.IncomingMessage) => {\n\t\t\t\tlet data = '';\n\t\t\t\tres.on('data', (chunk: Buffer) => {\n\t\t\t\t\tdata += chunk.toString();\n\t\t\t\t});\n\t\t\t\tres.on('end', () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresolve(JSON.parse(data));\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\treject(new Error(`Failed to parse response: ${err instanceof Error ? err.message : String(err)}`));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\n\t\t\treq.on('error', (err: Error) => {\n\t\t\t\treject(err);\n\t\t\t});\n\n\t\t\treq.write(postData);\n\t\t\treq.end();\n\t\t});\n\n\t\tvscode.window.showInformationMessage(`Response: ${JSON.stringify(json, null, 2)}`);\n\t} catch (err) {\n\t\tconst errorMessage = err instanceof Error ? err.message : String(err);\n\t\tvscode.window.showErrorMessage(`Request failed: ${errorMessage}`);\n\t}\n}\n\n// -------------------- Prompt Serialization Helpers --------------------\nfunction formatStdoutBlock(content: string): string {\n\tconst normalized = content ?? '';\n\treturn `<stdout>\n${normalized}\n</stdout>`;\n}\n\nfunction formatLineNumberedOutput(content: string, startLine?: number, endLine?: number): string {\n\tconst lines = content.split(/\r?\n/);\n\tconst total = (lines.length === 1 && lines[0] === '') ? 0 : lines.length;\n\tif (total === 0) {\n\t\treturn '';\n\t}\n\tconst s = startLine !== undefined ? Math.max(1, Math.min(startLine, total)) : 1;\n\tconst e = endLine !== undefined ? Math.max(s, Math.min(endLine, total)) : total;\n\tconst buf: string[] = [];\n\tfor (let idx = s; idx <= e; idx++) {\n\t\tconst lineText = lines[idx - 1] ?? '';\n\t\tbuf.push(`${idx.toString().padStart(6, ' ')}\t${lineText}`);\n\t}\n\treturn buf.join('\n');\n}\n\nfunction computeViewport(totalLines: number, centerLine: number, radius: number): { start: number; end: number } {\n\tif (totalLines <= 0) {\n\t\treturn { start: 1, end: 0 };\n\t}\n\tconst start = Math.max(1, centerLine - radius);\n\tconst end = Math.min(totalLines, centerLine + radius);\n\treturn { start, end };\n}\n\nfunction fencedBashBlock(command: string): string {\n\tconst cleaned = command.replace(/\r/g, '').trim();\n\treturn `\`\`\`bash\n${cleaned}\n\`\`\``;\n}\n\n// -------------------- Model-planned Actions --------------------\nasync function requestModelActions(editor: vscode.TextEditor, signal?: AbortSignal): Promise<PlannedAction> {\n\tconst config = vscode.workspace.getConfiguration();\n\t\n\tlet hostname: string;\n\tlet port: number;\n\tlet path: string;\n\tlet useHttps = true;\n\tlet modelName: string;\n\tconst headers: any = {\n\t\t'Content-Type': 'application/json'\n\t};\n\n\tif (!USE_GEMINI) {\n\t\t// SGLang\n\t\thostname = SGLANG_HOSTNAME;\n\t\tport = SGLANG_PORT;\n\t\tpath = SGLANG_BASE_PATH;\n\t\tuseHttps = false;\n\t\tmodelName = SGLANG_MODEL_NAME;\n\t} else {\n\t\t// Gemini\n\t\tconst apiKey = config.get<string>('crowd-pilot.apiKey');\n\t\tif (!apiKey) {\n\t\t\tvscode.window.showErrorMessage('Crowd Pilot: Please set your API Key in settings (crowd-pilot.apiKey).');\n\t\t\tthrow new Error('API key not set');\n\t\t}\n\t\thostname = GEMINI_HOSTNAME;\n\t\tport = GEMINI_PORT;\n\t\tpath = GEMINI_BASE_PATH;\n\t\theaders['Authorization'] = `Bearer ${apiKey}`;\n\t\tmodelName = GEMINI_MODEL_NAME;\n\t}\n\n\tconst doc = editor.document;\n\tconst cursor = editor.selection.active;\n\tconst fullText = doc.getText();\n\tconst filePath = doc.uri.fsPath;\n\tconst workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath ?? '(unknown)';\n\tconst cursorLine = cursor.line + 1;\n\tconst cursorColumn = cursor.character + 1;\n\tconst totalLines = doc.lineCount;\n\tconst viewport = computeViewport(totalLines, cursorLine, 12);\n\tconst metadataSummary = [\n\t\t`Workspace root: ${workspaceRoot}`,\n\t\t`Active file: ${filePath}`,\n\t\t`Language: ${doc.languageId}`,\n\t\t`Cursor (1-based): line ${cursorLine}, column ${cursorColumn}`\n\t].join('\n');\n\tconst metadataCommand = [\n\t\t""cat <<'EOF'"",\n\t\tmetadataSummary,\n\t\t'EOF'\n\t].join('\n');\n\n\tconst systemPrompt = [\n\t\t'You are a helpful assistant that can interact multiple times with a computer shell to solve programming tasks.',\n\t\t'Your response must contain exactly ONE bash code block with ONE command (or commands connected with && or ||).',\n\t\t'',\n\t\t'Format your response as shown in <format_example>.',\n\t\t'',\n\t\t'<format_example>',\n\t\t'```bash',\n\t\t'your_command_here',\n\t\t'```',\n\t\t'</format_example>',\n\t\t'',\n\t\t'Failure to follow these rules will cause your response to be rejected.',\n\t\t'',\n\t\t'=== EDIT COMMAND FORMAT (IMPORTANT) ===',\n\t\t'When you want to EDIT a file, you MUST encode the edit using line-based sed commands in ONE of the following forms,',\n\t\t'and you MUST NOT use substitution commands like ""Ns/old/new/g"".',\n\t\t'',\n\t\t'Assume all line numbers are 1-based and paths are absolute.',\n\t\t'Allowed edit encodings (choose exactly one per response):',\n\t\t'',\n\t\t'1) Replace a contiguous block of lines:',\n\t\t"" sed -i 'START,ENDc\\"",\n\t\t'NEW_LINE_1',\n\t\t'NEW_LINE_2',\n\t\t""..."",\n\t\t""' /abs/path/to/file && cat -n /abs/path/to/file | sed -n 'VSTART,VENDp'"",\n\t\t'',\n\t\t'2) Delete a contiguous block of lines:',\n\t\t"" sed -i 'START,ENDd' /abs/path/to/file && cat -n /abs/path/to/file | sed -n 'VSTART,VENDp'"",\n\t\t'',\n\t\t'3) Insert new lines BEFORE a given line:',\n\t\t"" sed -i 'STARTi\\"",\n\t\t'NEW_LINE_1',\n\t\t'NEW_LINE_2',\n\t\t""..."",\n\t\t""' /abs/path/to/file && cat -n /abs/path/to/file | sed -n 'VSTART,VENDp'"",\n\t\t'',\n\t\t'4) Append new lines at the END of the file:',\n\t\t"" sed -i '$a\\"",\n\t\t'NEW_LINE_1',\n\t\t'NEW_LINE_2',\n\t\t""..."",\n\t\t""' /abs/path/to/file && cat -n /abs/path/to/file | sed -n 'VSTART,VENDp'"",\n\t\t'',\n\t\t'Where VSTART and VEND specify a small viewport around the edited region.',\n\t\t'',\n\t\t'Do NOT emit commands like ""3s/print/print()/g"" or any other ""s/old/new/"" style sed substitution; instead,',\n\t\t'always rewrite the affected lines using one of the line-based forms above.',\n\t\t'',\n\t\t'When you are NOT editing files (e.g., running tests, git commands, tools, etc.), you may emit arbitrary bash commands.'\n\t].join('\n');\n\n\tconst conversationMessages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }> = [\n\t\t{ role: 'system', content: systemPrompt },\n\t\t{ role: 'assistant', content: fencedBashBlock(metadataCommand) },\n\t\t{ role: 'user', content: formatStdoutBlock(metadataSummary) },\n\t\t{ role: 'assistant', content: fencedBashBlock(`cat -n ${filePath}`) },\n\t\t{ role: 'user', content: formatStdoutBlock(formatLineNumberedOutput(fullText)) }\n\t];\n\n\tif (viewport.end >= viewport.start) {\n\t\tconst viewportOutput = formatLineNumberedOutput(fullText, viewport.start, viewport.end);\n\t\tconversationMessages.push(\n\t\t\t{ role: 'assistant', content: fencedBashBlock(`cat -n ${filePath} | sed -n '${viewport.start},${viewport.end}p'`) },\n\t\t\t{ role: 'user', content: formatStdoutBlock(viewportOutput) }\n\t\t);\n\t}\n\n\tconst requestBody: any = {\n\t\tmodel: modelName,\n\t\tmessages: conversationMessages\n\t};\n\tif (!USE_GEMINI) {\n\t\trequestBody.temperature = 0.7;\n\t\trequestBody.top_p = 0.8;\n\t\trequestBody.top_k = 20;\n\t\trequestBody.min_p = 0;\n\t\trequestBody.extra_body = {\n\t\t\tchat_template_kwargs: {\n\t\t\t\tenable_thinking: false\n\t\t\t}\n\t\t};\n\t}\n\n\tconst postData = JSON.stringify(requestBody);\n\theaders['Content-Length'] = Buffer.byteLength(postData);\n\n\tconst options: any = {\n\t\thostname,\n\t\tport,\n\t\tpath,\n\t\tmethod: 'POST',\n\t\theaders\n\t};\n\tif (signal) {\n\t\toptions.signal = signal;\n\t}\n\n\tconst requestModule = useHttps ? https : http;\n\n\tconst json = await new Promise<any>((resolve, reject) => {\n\t\tconst req = requestModule.request(options, (res: http.IncomingMessage) => {\n\t\t\tlet data = '';\n\t\t\tres.on('data', (chunk: Buffer) => { data += chunk.toString(); });\n\t\t\tres.on('end', () => {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(JSON.parse(data));\n\t\t\t\t} catch (err) {\n\t\t\t\t\treject(new Error(`Failed to parse response: ${err instanceof Error ? err.message : String(err)}`));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\treq.on('error', (err: Error) => reject(err));\n\t\treq.write(postData);\n\t\treq.end();\n\t});\n\n\tconst content = extractChatContent(json);\n\tif (typeof content !== 'string' || content.trim().length === 0) {\n\t\tthrow new Error('Empty model content');\n\t}\n\tconst action = parsePlannedAction(content, doc);\n\tif (!action) {\n\t\tthrow new Error('No valid action parsed from model output');\n\t}\n\treturn action;\n}\n\nfunction extractChatContent(json: any): string | undefined {\n\ttry {\n\t\tif (json && Array.isArray(json.choices) && json.choices[0]) {\n\t\t\tconst choice = json.choices[0];\n\t\t\tif (choice.message && typeof choice.message.content === 'string') {\n\t\t\t\treturn choice.message.content;\n\t\t\t}\n\t\t\tif (typeof choice.text === 'string') {\n\t\t\t\treturn choice.text;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction parsePlannedAction(raw: string, doc?: vscode.TextDocument): PlannedAction | undefined {\n\tconst command = extractBashCommand(raw);\n\tif (!command) {\n\t\treturn undefined;\n\t}\n\tconst normalized = command.replace(/<think>[\s\S]*?<\/think>/gi, '').trim();\n\tif (!normalized) {\n\t\treturn undefined;\n\t}\n\t// Try to interpret the command as a structured VS Code action derived from the bash transcript.\n\tif (doc) {\n\t\t// 1) Edits encoded as sed -i ... (insert/replace/delete)\n\t\tconst editAction = parseEditFromSedCommand(normalized, doc);\n\t\tif (editAction) {\n\t\t\treturn editAction;\n\t\t}\n\t\t// 2) Viewport / selection moves encoded as cat -n ... | sed -n 'vstart,vendp'\n\t\tconst viewportAction = parseViewportFromCatCommand(normalized, doc);\n\t\tif (viewportAction) {\n\t\t\treturn viewportAction;\n\t\t}\n\t}\n\t// Fallback: execute the raw command in the integrated terminal.\n\treturn { kind: 'terminalSendText', text: normalized };\n}\n\n/**\n * Parse a sed-based edit command of the form emitted by the NeMo serializer into a VS Code edit action.\n *\n * Supported patterns (1-based line numbers, mirroring serialization_utils.py):\n * sed -i 'START,ENDc\n<replacement...>' <file> -> editReplace\n * sed -i 'START,ENDd' <file> -> editDelete\n * sed -i 'STARTi\n<insert...>' <file> -> editInsert (before START)\n * sed -i '$a\n<append...>' <file> -> editInsert (append at EOF)\n *\n * If the command does not match these patterns, returns undefined.\n */\nfunction parseEditFromSedCommand(command: string, doc: vscode.TextDocument): PlannedAction | undefined {\n\t// Only consider the first command before && / ||, since cat -n etc. are for viewport only.\n\tconst main = command.split(/&&|\|\|/)[0]?.trim() ?? '';\n\tif (!main) {\n\t\treturn undefined;\n\t}\n\n\t// Match: sed -i '<script>' <file>\n\tconst sedMatch = main.match(/sed\s+-i\s+'([\s\S]*?)'\s+([^\s&|]+)\s*$/);\n\tif (!sedMatch) {\n\t\treturn undefined;\n\t}\n\tconst script = sedMatch[1] ?? '';\n\tconst targetFile = sedMatch[2] ?? '';\n\tconst activePath = doc.uri.fsPath;\n\t// Be conservative: only apply edits when the sed target matches the active document path.\n\tif (targetFile !== activePath) {\n\t\treturn undefined;\n\t}\n\n\t// Delete: ""START,ENDd""\n\tconst deleteMatch = script.match(/^(\d+),(\d+)d$/);\n\tif (deleteMatch) {\n\t\tconst startLine1 = Number(deleteMatch[1]);\n\t\tconst endLine1 = Number(deleteMatch[2]);\n\t\tif (!Number.isFinite(startLine1) || !Number.isFinite(endLine1)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst startLine0 = Math.max(0, startLine1 - 1);\n\t\tconst endLine0 = Math.max(0, endLine1 - 1);\n\n\t\tlet endPosLine = endLine0 + 1;\n\t\tlet endPosChar = 0;\n\t\tif (endPosLine >= doc.lineCount) {\n\t\t\tendPosLine = doc.lineCount - 1;\n\t\t\tendPosChar = doc.lineAt(endPosLine).range.end.character;\n\t\t}\n\t\treturn {\n\t\t\tkind: 'editDelete',\n\t\t\trange: {\n\t\t\t\tstart: [startLine0, 0],\n\t\t\t\tend: [endPosLine, endPosChar],\n\t\t\t},\n\t\t};\n\t}\n\n\t// Replace: ""START,ENDc\newline<payload...>""\n\tconst replaceMatch = script.match(/^(\d+),(\d+)c\\\n([\s\S]*)$/);\n\tif (replaceMatch) {\n\t\tconst startLine1 = Number(replaceMatch[1]);\n\t\tconst endLine1 = Number(replaceMatch[2]);\n\t\tlet payload = replaceMatch[3] ?? '';\n\t\tif (!Number.isFinite(startLine1) || !Number.isFinite(endLine1)) {\n\t\t\treturn undefined;\n\t\t}\n\t\t// Unescape single quotes as done in _escape_single_quotes_for_sed.\n\t\tpayload = payload.replace(/'\""'\""'/g, ""'"");\n\t\tconst startLine0 = Math.max(0, startLine1 - 1);\n\t\tconst endLine0 = Math.max(0, endLine1 - 1);\n\t\tconst startPos: [number, number] = [startLine0, 0];\n\n\t\t// Replace up to the start of the line after endLine, or end-of-document.\n\t\tlet endPosLine = endLine0 + 1;\n\t\tlet endPosChar = 0;\n\t\tif (endPosLine >= doc.lineCount) {\n\t\t\tendPosLine = doc.lineCount - 1;\n\t\t\tendPosChar = doc.lineAt(endPosLine).range.end.character;\n\t\t}\n\n\t\t// Preserve multi-line payload as-is; append a trailing newline so sed-style replacements map naturally.\n\t\tconst text = payload.endsWith('\n') ? payload : payload + '\n';\n\t\treturn {\n\t\t\tkind: 'editReplace',\n\t\t\trange: { start: startPos, end: [endPosLine, endPosChar] },\n\t\t\ttext,\n\t\t};\n\t}\n\n\t// Insert before a given line: ""STARTi\newline<payload...>""\n\tconst insertMatch = script.match(/^(\d+)i\\\n([\s\S]*)$/);\n\tif (insertMatch) {\n\t\tconst line1 = Number(insertMatch[1]);\n\t\tlet payload = insertMatch[2] ?? '';\n\t\tif (!Number.isFinite(line1)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tpayload = payload.replace(/'\""'\""'/g, ""'"");\n\t\tconst insertLine0 = Math.max(0, line1 - 1);\n\t\tconst position: [number, number] = [insertLine0, 0];\n\t\tconst text = payload.endsWith('\n') ? payload : payload + '\n';\n\t\treturn {\n\t\t\tkind: 'editInsert',\n\t\t\tposition,\n\t\t\ttext,\n\t\t};\n\t}\n\n\t// Append at end of file: ""$a\newline<payload...>""\n\tconst appendMatch = script.match(/^\$a\\\n([\s\S]*)$/);\n\tif (appendMatch) {\n\t\tlet payload = appendMatch[1] ?? '';\n\t\tpayload = payload.replace(/'\""'\""'/g, ""'"");\n\t\tconst insertLine0 = doc.lineCount;\n\t\tconst position: [number, number] = [insertLine0, 0];\n\t\tconst needsLeadingNewline = doc.lineCount > 0;\n\t\tconst base = payload.endsWith('\n') ? payload : payload + '\n';\n\t\tconst text = needsLeadingNewline ? '\n' + base : base;\n\t\treturn {\n\t\t\tkind: 'editInsert',\n\t\t\tposition,\n\t\t\ttext,\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Parse viewport / selection commands of the form:\n * cat -n <file> | sed -n 'START,ENDp'\n *\n * into a lightweight VS Code selection move (setSelections). This mirrors how\n * selection and viewport events are serialized in serialization_utils.py.\n */\nfunction parseViewportFromCatCommand(command: string, doc: vscode.TextDocument): PlannedAction | undefined {\n\tconst main = command.split(/&&|\|\|/)[0]?.trim() ?? '';\n\tif (!main) {\n\t\treturn undefined;\n\t}\n\n\t// Simple file-open: cat -n <file>\n\tconst simpleCatMatch = main.match(/^cat\s+-n\s+([^\s|]+)\s*$/);\n\tif (simpleCatMatch) {\n\t\tconst targetFile = simpleCatMatch[1] ?? '';\n\t\tif (targetFile !== doc.uri.fsPath) {\n\t\t\treturn undefined;\n\t\t}\n\t\t// Ensure the active document is visible; rely on existing editor to handle this.\n\t\treturn { kind: 'showTextDocument' };\n\t}\n\n\t// Viewport slice: cat -n <file> | sed -n 'START,ENDp'\n\tconst viewportMatch = main.match(/^cat\s+-n\s+([^\s|]+)\s*\|\s*sed\s+-n\s+'(\d+),(\d+)p'\s*$/);\n\tif (!viewportMatch) {\n\t\treturn undefined;\n\t}\n\n\tconst targetFile = viewportMatch[1] ?? '';\n\tconst startStr = viewportMatch[2] ?? '';\n\tconst endStr = viewportMatch[3] ?? '';\n\n\tif (targetFile !== doc.uri.fsPath) {\n\t\treturn undefined;\n\t}\n\n\tconst startLine1 = Number(startStr);\n\tconst endLine1 = Number(endStr);\n\tif (!Number.isFinite(startLine1) || !Number.isFinite(endLine1)) {\n\t\treturn undefined;\n\t}\n\n\t// Place the cursor in the middle of the viewport (1-based to 0-based).\n\tconst center1 = Math.floor((startLine1 + endLine1) / 2);\n\tconst center0 = Math.max(0, center1 - 1);\n\tconst lastLine = Math.max(0, doc.lineCount - 1);\n\tconst line = Math.min(center0, lastLine);\n\tconst endChar = doc.lineAt(line).range.end.character;\n\n\treturn {\n\t\tkind: 'setSelections',\n\t\tselections: [\n\t\t\t{\n\t\t\t\tstart: [line, endChar],\n\t\t\t\tend: [line, endChar],\n\t\t\t},\n\t\t],\n\t};\n}\n\nfunction extractBashCommand(raw: string): string | undefined {\n\tif (!raw) {\n\t\treturn undefined;\n\t}\n\tconst trimmed = raw.trim();\n\tconst fenceMatch = trimmed.match(/```(?:bash)?\s*([\s\S]*?)```/i);\n\tif (fenceMatch && fenceMatch[1]) {\n\t\treturn fenceMatch[1];\n\t}\n\t// Fallback: treat entire response as the command\n\treturn trimmed.length > 0 ? trimmed : undefined;\n}",typescript,tab
|
| 10 |
+
9,96355,"src/extension.ts",131,0,"",typescript,selection_command
|
| 11 |
+
10,220406,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"",Log,tab
|
| 12 |
+
11,222329,"TERMINAL",0,0,"",,terminal_focus
|
| 13 |
+
12,222330,"src/extension.ts",0,0,"",typescript,tab
|
| 14 |
+
13,225181,"TERMINAL",0,0,"bash",,terminal_focus
|
| 15 |
+
14,226900,"TERMINAL",0,0,"squeue",,terminal_command
|
| 16 |
+
15,226908,"TERMINAL",0,0,"]633;C JOBID USER PARTITION NODES CPUS ST SUBMIT_TIME START_TIME TIME TIME_LIMIT NODELIST(REASON)\r\n 35374 alfred.ngu interacti 1 8 R 2025-12-04T18:02:52 2025-12-04T18:02:52 50:40 2:00:00 hai005\r\n 35372 mihir.maha interacti 1 2 R 2025-12-04T17:13:56 2025-12-04T17:13:56 1:39:36 2:00:00 hai008\r\n 35370 franz.sram interacti 1 20 R 2025-12-04T16:09:04 2025-12-04T16:09:04 2:44:28 1-00:00:00 hai007\r\n 35369 xiao.liu interacti 1 128 R 2025-12-04T15:57:08 2025-12-04T15:57:08 2:56:24 23:59:00 hai006\r\n 35327 xiao.liu interacti 1 128 R 2025-12-04T05:49:37 2025-12-04T05:49:37 13:03:55 23:59:00 hai005\r\n 35375 nishant.ku standard 3 624 R 2025-12-04T18:05:21 2025-12-04T18:05:21 48:11 1-00:00:00 hai[001-003]\r\n 35359 xiao.liu standard 1 128 R 2025-12-04T14:17:52 2025-12-04T15:52:37 3:00:55 23:59:00 hai004\r\n]0;franz.srambical@hai-login2:~/crowd-pilot-extension",,terminal_output
|
| 17 |
+
16,333341,"TERMINAL",0,0,"scancel --me",,terminal_command
|
| 18 |
+
17,333356,"TERMINAL",0,0,"]633;C]0;franz.srambical@hai-login2:~/crowd-pilot-extension",,terminal_output
|
| 19 |
+
18,335038,"TERMINAL",0,0,"squeue",,terminal_command
|
| 20 |
+
19,335050,"TERMINAL",0,0,"]633;C JOBID USER PARTITION NODES CPUS ST SUBMIT_TIME START_TIME TIME TIME_LIMIT NODELIST(REASON)\r\n 35370 franz.sram interacti 1 20 CG 2025-12-04T16:09:04 2025-12-04T16:09:04 2:46:15 1-00:00:00 hai007\r\n 35374 alfred.ngu interacti 1 8 R 2025-12-04T18:02:52 2025-12-04T18:02:52 52:29 2:00:00 hai005\r\n 35372 mihir.maha interacti 1 2 R 2025-12-04T17:13:56 2025-12-04T17:13:56 1:41:25 2:00:00 hai008\r\n 35369 xiao.liu interacti 1 128 R 2025-12-04T15:57:08 2025-12-04T15:57:08 2:58:13 23:59:00 hai006\r\n 35327 xiao.liu interacti 1 128 R 2025-12-04T05:49:37 2025-12-04T05:49:37 13:05:44 23:59:00 hai005\r\n 35375 nishant.ku standard 3 624 R 2025-12-04T18:05:21 2025-12-04T18:05:21 50:00 1-00:00:00 hai[001-003]\r\n 35359 xiao.liu standard 1 128 R 2025-12-04T14:17:52 2025-12-04T15:52:37 3:02:44 23:59:00 hai004\r\n]0;franz.srambical@hai-login2:~/crowd-pilot-extension",,terminal_output
|
| 21 |
+
20,339739,"src/extension.ts",0,0,"",typescript,tab
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-67216304-51bb-4456-bf20-d9a7d43f4abc1762614700573-2025_11_08-16.11.46.209/source.csv
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Sequence,Time,File,RangeOffset,RangeLength,Text,Language,Type
|
| 2 |
+
1,2,"Untitled-1",0,0,"",plaintext,tab
|
| 3 |
+
2,176,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"4:11:46 PM [info] Activating crowd-code\n4:11:46 PM [info] Recording started\n4:11:46 PM [info] Initializing git provider using file system watchers...\n4:11:46 PM [info] No workspace folder found\n",Log,tab
|
| 4 |
+
3,961,"Untitled-1",0,0,"",plaintext,tab
|
| 5 |
+
4,9250,"Untitled-1",0,0,"{\n ""name"": ""crowd-pilot"",\n ""displayName"": ""crowd-pilot-extension"",\n ""description"": ""Teaching language models to code like humans."",\n ""publisher"": ""p(doom)"",\n ""version"": ""0.0.1"",\n ""engines"": {\n ""vscode"": ""^1.99.3""\n },\n ""categories"": [\n ""Other""\n ],\n ""activationEvents"": [\n ""onStartupFinished""\n ],\n ""main"": ""./out/extension.js"",\n ""contributes"": {\n ""commands"": [\n {\n ""command"": ""crowd-pilot.testRun"",\n ""title"": ""Test Run""\n },\n {\n ""command"": ""crowd-pilot.hideUi"",\n ""title"": ""crowd-pilot: Hide Preview""\n },\n {\n ""command"": ""crowd-pilot.sglangTest"",\n ""title"": ""crowd-pilot: Test SGLang""\n },\n {\n ""command"": ""crowd-pilot.modelRun"",\n ""title"": ""crowd-pilot: Model Plan & Run""\n }\n ],\n ""keybindings"": [\n {\n ""command"": ""crowd-pilot.modelRun"",\n ""key"": ""tab"",\n ""mac"": ""tab"",\n ""when"": ""editorTextFocus || terminalFocus""\n },\n {\n ""command"": ""crowd-pilot.modelRun"",\n ""key"": ""tab"",\n ""mac"": ""tab"",\n ""when"": ""inQuickOpen && crowdPilot.uiVisible""\n },\n {\n ""command"": ""crowd-pilot.hideUi"",\n ""key"": ""escape"",\n ""mac"": ""escape"",\n ""when"": ""crowdPilot.uiVisible""\n }\n ]\n },\n ""scripts"": {\n ""vscode:prepublish"": ""npm run compile"",\n ""compile"": ""tsc -p ./"",\n ""watch"": ""tsc -watch -p ./"",\n ""pretest"": ""npm run compile && npm run lint"",\n ""lint"": ""eslint src"",\n ""test"": ""vscode-test""\n },\n ""devDependencies"": {\n ""@types/vscode"": ""^1.105.0"",\n ""@types/mocha"": ""^10.0.10"",\n ""@types/node"": ""22.x"",\n ""@typescript-eslint/eslint-plugin"": ""^8.45.0"",\n ""@typescript-eslint/parser"": ""^8.45.0"",\n ""eslint"": ""^9.36.0"",\n ""typescript"": ""^5.9.3"",\n ""@vscode/test-cli"": ""^0.0.11"",\n ""@vscode/test-electron"": ""^2.5.2""\n }\n}\n",plaintext,content
|
| 6 |
+
5,9762,"Untitled-1",0,0,"",plaintext,selection_command
|
| 7 |
+
6,12696,"Untitled-1",291,0,"",json,selection_command
|
| 8 |
+
7,13083,"Untitled-1",308,0,"",json,selection_command
|
| 9 |
+
8,13264,"Untitled-1",312,0,"",json,selection_command
|
| 10 |
+
9,13677,"Untitled-1",308,0,"",json,selection_command
|
| 11 |
+
10,14157,"Untitled-1",307,0,"",json,selection_command
|
| 12 |
+
11,14412,"Untitled-1",306,0,"",json,selection_command
|
| 13 |
+
12,14439,"Untitled-1",305,0,"",json,selection_command
|
| 14 |
+
13,14471,"Untitled-1",304,0,"",json,selection_command
|
| 15 |
+
14,14505,"Untitled-1",303,0,"",json,selection_command
|
| 16 |
+
15,14536,"Untitled-1",302,0,"",json,selection_command
|
| 17 |
+
16,14571,"Untitled-1",301,0,"",json,selection_command
|
| 18 |
+
17,14603,"Untitled-1",300,0,"",json,selection_command
|
| 19 |
+
18,14638,"Untitled-1",299,0,"",json,selection_command
|
| 20 |
+
19,14670,"Untitled-1",298,0,"",json,selection_command
|
| 21 |
+
20,14705,"Untitled-1",297,0,"",json,selection_command
|
| 22 |
+
21,14737,"Untitled-1",296,0,"",json,selection_command
|
| 23 |
+
22,14769,"Untitled-1",295,0,"",json,selection_command
|
| 24 |
+
23,14809,"Untitled-1",294,0,"",json,selection_command
|
| 25 |
+
24,15568,"Untitled-1",295,0,"",json,selection_command
|
| 26 |
+
25,15744,"Untitled-1",296,0,"",json,selection_command
|
| 27 |
+
26,16876,"Untitled-1",297,0,"",json,selection_command
|
| 28 |
+
27,17178,"Untitled-1",298,0,"",json,selection_command
|
| 29 |
+
28,17319,"Untitled-1",299,0,"",json,selection_command
|
| 30 |
+
29,17476,"Untitled-1",300,0,"",json,selection_command
|
| 31 |
+
30,17801,"Untitled-1",301,0,"",json,selection_command
|
| 32 |
+
31,18366,"Untitled-1",301,8,"",json,content
|
| 33 |
+
32,18558,"Untitled-1",301,0,"i",json,content
|
| 34 |
+
33,18559,"Untitled-1",302,0,"",json,selection_keyboard
|
| 35 |
+
34,18906,"Untitled-1",302,0,"nished"",",json,content
|
| 36 |
+
35,19792,"Untitled-1",309,0,"",json,selection_command
|
| 37 |
+
36,19872,"Untitled-1",308,0,"",json,selection_command
|
| 38 |
+
37,20068,"Untitled-1",291,0,"",json,selection_command
|
| 39 |
+
38,20582,"Untitled-1",292,0,"",json,selection_command
|
| 40 |
+
39,20833,"Untitled-1",293,0,"",json,selection_command
|
| 41 |
+
40,20886,"Untitled-1",294,0,"",json,selection_command
|
| 42 |
+
41,20896,"Untitled-1",295,0,"",json,selection_command
|
| 43 |
+
42,20937,"Untitled-1",296,0,"",json,selection_command
|
| 44 |
+
43,20962,"Untitled-1",297,0,"",json,selection_command
|
| 45 |
+
44,20994,"Untitled-1",298,0,"",json,selection_command
|
| 46 |
+
45,21019,"Untitled-1",299,0,"",json,selection_command
|
| 47 |
+
46,21054,"Untitled-1",300,0,"",json,selection_command
|
| 48 |
+
47,21089,"Untitled-1",301,0,"",json,selection_command
|
| 49 |
+
48,21661,"Untitled-1",301,9,"",json,content
|
| 50 |
+
49,24215,"Untitled-1",301,0,"i",json,content
|
| 51 |
+
50,24216,"Untitled-1",302,0,"",json,selection_keyboard
|
| 52 |
+
51,24624,"Untitled-1",302,0,"nished:extension/crowd-pilot""",json,content
|
| 53 |
+
52,28054,"Untitled-1",330,0,"",json,selection_command
|
| 54 |
+
53,30751,"Untitled-1",331,0,",",json,content
|
| 55 |
+
54,30755,"Untitled-1",308,22,"",json,content
|
| 56 |
+
55,30758,"Untitled-1",301,0,"",json,selection_command
|
| 57 |
+
56,32269,"Untitled-1",301,9,"",json,content
|
| 58 |
+
57,32697,"Untitled-1",301,0,"i",json,content
|
| 59 |
+
58,32698,"Untitled-1",302,0,"",json,selection_keyboard
|
| 60 |
+
59,33765,"Untitled-1",301,0,"",json,selection_command
|
| 61 |
+
60,34300,"Untitled-1",302,0,"",json,selection_command
|
| 62 |
+
61,38698,"Untitled-1",302,0,"le:startupFinished",json,content
|
| 63 |
+
62,41684,"Untitled-1",319,0,"",json,selection_command
|
| 64 |
+
63,42758,"Untitled-1",284,0,"",json,selection_command
|
| 65 |
+
64,42905,"Untitled-1",319,0,"",json,selection_command
|
| 66 |
+
65,44123,"Untitled-1",320,0,"",json,selection_command
|
| 67 |
+
66,44268,"Untitled-1",320,0,"""",json,content
|
| 68 |
+
67,45773,"Untitled-1",320,1,"",json,content
|
| 69 |
+
68,46077,"Untitled-1",320,0,"""",json,content
|
| 70 |
+
69,46077,"Untitled-1",317,3,"",json,content
|
| 71 |
+
70,46077,"Untitled-1",316,0,".j",json,content
|
| 72 |
+
71,46077,"Untitled-1",312,4,"",json,content
|
| 73 |
+
72,48194,"Untitled-1",315,1,"hed""",json,content
|
| 74 |
+
73,48194,"Untitled-1",312,2,"Fini",json,content
|
| 75 |
+
74,49057,"Untitled-1",320,1,"",json,content
|
| 76 |
+
75,49355,"Untitled-1",320,0,"""",json,content
|
| 77 |
+
76,49355,"Untitled-1",317,3,"",json,content
|
| 78 |
+
77,49355,"Untitled-1",316,0,".t",json,content
|
| 79 |
+
78,49355,"Untitled-1",312,4,"",json,content
|
| 80 |
+
79,50261,"Untitled-1",315,1,"hed""",json,content
|
| 81 |
+
80,50262,"Untitled-1",312,2,"Fini",json,content
|
| 82 |
+
81,50614,"Untitled-1",320,1,"",json,content
|
| 83 |
+
82,51172,"Untitled-1",319,0,"",json,selection_command
|
| 84 |
+
83,51601,"Untitled-1",320,0,"",json,selection_command
|
| 85 |
+
84,55718,"Untitled-1",320,0,"""",json,content
|
| 86 |
+
85,55719,"Untitled-1",321,0,"",json,selection_keyboard
|
| 87 |
+
86,56534,"Untitled-1",320,0,"",json,selection_command
|
| 88 |
+
87,57148,"Untitled-1",325,0,"",json,selection_command
|
| 89 |
+
88,57240,"Untitled-1",357,0,"",json,selection_command
|
| 90 |
+
89,67058,"Untitled-1",376,0,"",json,selection_command
|
| 91 |
+
90,67312,"Untitled-1",394,0,"",json,selection_command
|
| 92 |
+
91,67337,"Untitled-1",402,0,"",json,selection_command
|
| 93 |
+
92,67367,"Untitled-1",438,0,"",json,selection_command
|
| 94 |
+
93,67400,"Untitled-1",472,0,"",json,selection_command
|
| 95 |
+
94,67779,"Untitled-1",481,0,"",json,selection_command
|
| 96 |
+
95,68025,"Untitled-1",489,0,"",json,selection_command
|
| 97 |
+
96,68058,"Untitled-1",525,0,"",json,selection_command
|
| 98 |
+
97,68090,"Untitled-1",566,0,"",json,selection_command
|
| 99 |
+
98,69049,"Untitled-1",584,0,"",json,selection_command
|
| 100 |
+
99,69308,"Untitled-1",592,0,"",json,selection_command
|
| 101 |
+
100,69345,"Untitled-1",628,0,"",json,selection_command
|
| 102 |
+
101,69366,"Untitled-1",673,0,"",json,selection_command
|
| 103 |
+
102,70691,"Untitled-1",670,0,"",json,selection_command
|
| 104 |
+
103,70848,"Untitled-1",668,0,"",json,selection_command
|
| 105 |
+
104,71024,"Untitled-1",663,0,"",json,selection_command
|
| 106 |
+
105,71681,"Untitled-1",664,0,"",json,selection_command
|
| 107 |
+
106,72274,"Untitled-1",664,18,"",json,content
|
| 108 |
+
107,72664,"Untitled-1",664,0,"i",json,content
|
| 109 |
+
108,72665,"Untitled-1",665,0,"",json,selection_keyboard
|
| 110 |
+
109,76786,"Untitled-1",665,0,"lot Test",json,content
|
| 111 |
+
110,80580,"Untitled-1",672,0,"",json,selection_command
|
| 112 |
+
111,80937,"Untitled-1",673,0,"",json,selection_command
|
| 113 |
+
112,82888,"Untitled-1",673,0," Run",json,content
|
| 114 |
+
113,83935,"Untitled-1",676,0,"",json,selection_command
|
| 115 |
+
114,85532,"Untitled-1",676,0,"n",json,content
|
| 116 |
+
115,86356,"Untitled-1",677,1,"",json,content
|
| 117 |
+
116,86357,"Untitled-1",676,0,"",json,selection_command
|
| 118 |
+
117,87233,"Untitled-1",677,0,"",json,selection_command
|
| 119 |
+
118,87390,"Untitled-1",677,0," SGLang""",json,content
|
| 120 |
+
119,88414,"Untitled-1",684,1,"",json,content
|
| 121 |
+
120,88658,"Untitled-1",683,1,"",json,content
|
| 122 |
+
121,88694,"Untitled-1",682,1,"",json,content
|
| 123 |
+
122,88732,"Untitled-1",681,1,"",json,content
|
| 124 |
+
123,88853,"Untitled-1",680,1,"",json,content
|
| 125 |
+
124,89002,"Untitled-1",679,1,"",json,content
|
| 126 |
+
125,89153,"Untitled-1",678,1,"",json,content
|
| 127 |
+
126,89308,"Untitled-1",677,1,"",json,content
|
| 128 |
+
127,89621,"Untitled-1",677,0," (SGLang)""",json,content
|
| 129 |
+
128,90387,"Untitled-1",686,1,"",json,content
|
| 130 |
+
129,90621,"Untitled-1",685,1,"",json,content
|
| 131 |
+
130,90648,"Untitled-1",684,1,"",json,content
|
| 132 |
+
131,90688,"Untitled-1",683,1,"",json,content
|
| 133 |
+
132,90723,"Untitled-1",682,1,"",json,content
|
| 134 |
+
133,90749,"Untitled-1",681,1,"",json,content
|
| 135 |
+
134,90787,"Untitled-1",680,1,"",json,content
|
| 136 |
+
135,90819,"Untitled-1",679,1,"",json,content
|
| 137 |
+
136,90854,"Untitled-1",678,1,"",json,content
|
| 138 |
+
137,90964,"Untitled-1",677,1,"",json,content
|
| 139 |
+
138,91553,"Untitled-1",676,0,"",json,selection_command
|
| 140 |
+
139,91809,"Untitled-1",677,0,"",json,selection_command
|
| 141 |
+
140,95481,"Untitled-1",677,0,"""}]",json,content
|
| 142 |
+
141,96812,"Untitled-1",679,0,"",json,selection_command
|
| 143 |
+
142,98516,"Untitled-1",678,0,"",json,selection_command
|
| 144 |
+
143,99319,"Untitled-1",679,0,"",json,selection_command
|
| 145 |
+
144,99677,"Untitled-1",678,0,"",json,selection_command
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-67b923a6-2474-4a8c-924a-d100648f06ad1759141988418-2025_09_29-12.33.17.507/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-6848d624-e3ad-4152-9883-dc056cdeb99d1754923670198-2025_08_11-16.48.03.201/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-6a2b9de9-16b6-4ba2-9a19-eff03fad03561755414648588-2025_08_17-09.12.59.520/source.csv
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Sequence,Time,File,RangeOffset,RangeLength,Text,Language,Type
|
| 2 |
+
1,3,"train_dynamics.py",0,0,"from dataclasses import dataclass, field\nimport os\nfrom typing import cast\n\nimport einops\nfrom jax.sharding import Mesh, PartitionSpec, NamedSharding\nfrom jax.experimental.mesh_utils import create_device_mesh\nimport optax\nimport orbax.checkpoint as ocp\nimport numpy as np\nimport dm_pix as pix\nimport jax\nimport jax.numpy as jnp\nimport tyro\nimport wandb\nimport grain\nimport flax.nnx as nnx\n\nfrom genie import Genie, restore_genie_components\nfrom utils.dataloader import get_dataloader\nfrom utils.lr_utils import get_lr_schedule\nfrom utils.parameter_utils import count_parameters_by_component\n\n\n@dataclass\nclass Args:\n # Experiment\n num_steps: int = 200_000\n seed: int = 0\n seq_len: int = 16\n image_channels: int = 3\n image_height: int = 90\n image_width: int = 160\n data_dir: str = """"\n save_ckpt: bool = False\n restore_ckpt: bool = False\n # Optimization\n batch_size: int = 36\n init_lr: float = 0.0\n max_lr: float = 3e-5\n decay_end: float = 0.0\n wsd_decay_steps: int = (\n 10000 # NOTE: wsd_decay_steps will only be used when using a wsd-schedule\n )\n warmup_steps: int = 5000\n lr_schedule: str = ""wsd"" # supported options: wsd, cos\n # Tokenizer\n tokenizer_dim: int = 512\n tokenizer_ffn_dim: int = 2048\n latent_patch_dim: int = 32\n num_patch_latents: int = 1024\n patch_size: int = 4\n tokenizer_num_blocks: int = 4\n tokenizer_num_heads: int = 8\n tokenizer_checkpoint: str = """"\n # LAM\n lam_dim: int = 512\n lam_ffn_dim: int = 2048\n latent_action_dim: int = 32\n num_latent_actions: int = 6\n lam_patch_size: int = 16\n lam_num_blocks: int = 4\n lam_num_heads: int = 8\n lam_checkpoint: str = """"\n # Dynamics\n dyna_type: str = ""maskgit"" # supported options: maskgit, causal\n dyna_dim: int = 512\n dyna_ffn_dim: int = 2048\n dyna_num_blocks: int = 6\n dyna_num_heads: int = 8\n dropout: float = 0.0\n mask_limit: float = 0.5\n param_dtype = jnp.float32\n dtype = jnp.bfloat16\n use_flash_attention: bool = True\n # Logging\n log: bool = False\n entity: str = """"\n project: str = """"\n name: str = ""train_dynamics""\n tags: list[str] = field(default_factory=lambda: [""dynamics""])\n log_interval: int = 5\n log_image_interval: int = 250\n ckpt_dir: str = """"\n log_checkpoint_interval: int = 25000\n log_checkpoint_keep_period: int = 20000\n log_gradients: bool = False\n wandb_id: str = """"\n\n\nargs = tyro.cli(Args)\n\n\ndef dynamics_loss_fn(\n model: Genie, inputs: dict\n) -> tuple[jax.Array, tuple[jax.Array, dict]]:\n """"""Compute masked dynamics loss""""""\n # gt = jnp.asarray(inputs[""videos""], dtype=jnp.float32) / 255.0\n # inputs[""videos""] = gt.astype(args.dtype)\n model.train()\n outputs = model(inputs, training=True)\n mask = outputs[""mask""]\n outputs[""token_logits""] = outputs[""token_logits""].astype(jnp.float32)\n ce_loss = optax.softmax_cross_entropy_with_integer_labels(\n outputs[""token_logits""], outputs[""video_tokens""]\n )\n ce_loss = (mask * ce_loss).sum() / mask.sum()\n acc = outputs[""token_logits""].argmax(-1) == outputs[""video_tokens""]\n acc = (mask * acc).sum() / mask.sum()\n select_probs = jax.nn.softmax(outputs[""token_logits""])\n # gt = gt.clip(0, 1).reshape(-1, *gt.shape[2:])\n # recon = outputs[""recon""].clip(0, 1).reshape(-1, *outputs[""recon""].shape[2:])\n # psnr = jnp.asarray(pix.psnr(gt, recon)).mean()\n # ssim = jnp.asarray(pix.ssim(gt, recon)).mean()\n # _, index_counts_lam = jnp.unique_counts(\n # jnp.ravel(outputs[""lam_indices""]), size=args.num_latent_actions, fill_value=0\n # )\n _, index_counts_tokenizer = jnp.unique_counts(\n jnp.ravel(outputs[""video_tokens""]), size=args.num_patch_latents, fill_value=0\n )\n # codebook_usage_lam = (index_counts_lam != 0).mean()\n codebook_usage_tokenizer = (index_counts_tokenizer != 0).mean()\n metrics = dict(\n cross_entropy_loss=ce_loss,\n masked_token_accuracy=acc,\n select_logit=outputs[""token_logits""].max(-1).mean(),\n select_p=select_probs.max(-1).mean(),\n entropy=jax.scipy.special.entr(select_probs).sum(-1).mean(),\n # psnr=psnr,\n # ssim=ssim,\n # codebook_usage_lam=codebook_usage_lam,\n codebook_usage_tokenizer=codebook_usage_tokenizer,\n )\n return ce_loss, (None, metrics)\n\n\n@nnx.jit\ndef train_step(\n model: Genie, optimizer: nnx.Optimizer, inputs: dict\n) -> tuple[jax.Array, jax.Array, dict]:\n """"""Update state and compute metrics""""""\n\n def loss_fn(model: Genie) -> tuple[jax.Array, tuple[jax.Array, dict]]:\n return dynamics_loss_fn(model, inputs)\n\n (loss, (recon, metrics)), grads = nnx.value_and_grad(loss_fn, has_aux=True)(model)\n optimizer.update(grads)\n if args.log_gradients:\n metrics[""gradients_std/""] = jax.tree.map(\n lambda x: x.std(), grads[""params""][""dynamics""]\n )\n return loss, recon, metrics\n\n\nif __name__ == ""__main__"":\n jax.distributed.initialize()\n num_devices = jax.device_count()\n if num_devices == 0:\n raise ValueError(""No JAX devices found."")\n print(f""Running on {num_devices} devices."")\n\n if args.batch_size % num_devices != 0:\n raise ValueError(\n f""Global batch size {args.batch_size} must be divisible by ""\n f""number of devices {num_devices}.""\n )\n\n per_device_batch_size_for_init = args.batch_size // num_devices\n\n rng = jax.random.key(args.seed)\n\n # --- Initialize model ---\n rng, _rng = jax.random.split(rng)\n rngs = nnx.Rngs(_rng)\n genie = Genie(\n # Tokenizer\n in_dim=args.image_channels,\n tokenizer_dim=args.tokenizer_dim,\n tokenizer_ffn_dim=args.tokenizer_ffn_dim,\n latent_patch_dim=args.latent_patch_dim,\n num_patch_latents=args.num_patch_latents,\n patch_size=args.patch_size,\n tokenizer_num_blocks=args.tokenizer_num_blocks,\n tokenizer_num_heads=args.tokenizer_num_heads,\n # LAM\n lam_dim=args.lam_dim,\n lam_ffn_dim=args.lam_ffn_dim,\n latent_action_dim=args.latent_action_dim,\n num_latent_actions=args.num_latent_actions,\n lam_patch_size=args.lam_patch_size,\n lam_num_blocks=args.lam_num_blocks,\n lam_num_heads=args.lam_num_heads,\n lam_co_train=not args.lam_checkpoint,\n # Dynamics\n dyna_type=args.dyna_type,\n dyna_dim=args.dyna_dim,\n dyna_ffn_dim=args.dyna_ffn_dim,\n dyna_num_blocks=args.dyna_num_blocks,\n dyna_num_heads=args.dyna_num_heads,\n dropout=args.dropout,\n mask_limit=args.mask_limit,\n param_dtype=args.param_dtype,\n dtype=args.dtype,\n use_flash_attention=args.use_flash_attention,\n decode=False,\n rngs=rngs,\n )\n\n _, params, _ = nnx.split(genie, nnx.Param, ...)\n param_counts = count_parameters_by_component(params)\n\n if args.log and jax.process_index() == 0:\n wandb_init_kwargs = {\n ""entity"": args.entity,\n ""project"": args.project,\n ""name"": args.name,\n ""tags"": args.tags,\n ""group"": ""debug"",\n ""config"": args,\n }\n\n if args.wandb_id:\n wandb_init_kwargs.update(\n {\n ""id"": args.wandb_id,\n ""resume"": ""allow"",\n }\n )\n wandb.init(**wandb_init_kwargs)\n\n wandb.config.update({""model_param_count"": param_counts})\n\n print(""Parameter counts:"")\n print(param_counts)\n\n # --- Initialize optimizer ---\n lr_schedule = get_lr_schedule(\n args.lr_schedule,\n args.init_lr,\n args.max_lr,\n args.decay_end,\n args.num_steps,\n args.warmup_steps,\n args.wsd_decay_steps,\n )\n tx = optax.adamw(\n learning_rate=lr_schedule,\n b1=0.9,\n b2=0.9,\n weight_decay=1e-4,\n mu_dtype=args.dtype,\n )\n optimizer = nnx.Optimizer(genie, tx)\n del genie\n\n # FIXME: switch to create_hybrid_device_mesh for runs spanning multiple nodes\n device_mesh_arr = create_device_mesh((num_devices,))\n mesh = Mesh(devices=device_mesh_arr, axis_names=(""data"",))\n\n replicated_sharding = NamedSharding(mesh, PartitionSpec())\n videos_sharding = NamedSharding(mesh, PartitionSpec(""data"", None, None, None, None))\n\n model_state = nnx.state(optimizer.model)\n model_sharded_state = jax.lax.with_sharding_constraint(\n model_state, replicated_sharding\n )\n nnx.update(optimizer.model, model_sharded_state)\n optimizer_state = nnx.state(optimizer, nnx.optimizer.OptState)\n optimizer_sharded_state = jax.lax.with_sharding_constraint(\n optimizer_state, replicated_sharding\n )\n nnx.update(optimizer, optimizer_sharded_state)\n\n # --- Initialize checkpoint manager ---\n step = 0\n handler_registry = ocp.handlers.DefaultCheckpointHandlerRegistry()\n handler_registry.add(\n ""model_state"", ocp.args.PyTreeSave, ocp.handlers.PyTreeCheckpointHandler\n )\n handler_registry.add(\n ""model_state"", ocp.args.PyTreeRestore, ocp.handlers.PyTreeCheckpointHandler\n )\n handler_registry.add(\n ""dataloader_state"",\n grain.checkpoint.CheckpointSave,\n cast(ocp.handlers.CheckpointHandler, grain.checkpoint.CheckpointHandler),\n )\n handler_registry.add(\n ""dataloader_state"",\n grain.checkpoint.CheckpointRestore,\n cast(ocp.handlers.CheckpointHandler, grain.checkpoint.CheckpointHandler),\n )\n\n checkpoint_options = ocp.CheckpointManagerOptions(\n save_interval_steps=args.log_checkpoint_interval,\n max_to_keep=3,\n keep_period=args.log_checkpoint_keep_period,\n step_format_fixed_length=6,\n cleanup_tmp_directories=True,\n )\n\n checkpoint_manager = ocp.CheckpointManager(\n args.ckpt_dir,\n options=checkpoint_options,\n handler_registry=handler_registry,\n )\n\n # --- Create DataLoaderIterator from dataloader ---\n image_shape = (args.image_height, args.image_width, args.image_channels)\n array_record_files = [\n os.path.join(args.data_dir, x)\n for x in os.listdir(args.data_dir)\n if x.endswith("".array_record"")\n ]\n grain_dataloader = get_dataloader(\n array_record_files,\n args.seq_len,\n # NOTE: We deliberately pass the global batch size\n # The dataloader shards the dataset across all processes\n args.batch_size,\n *image_shape,\n num_workers=8,\n prefetch_buffer_size=1,\n seed=args.seed,\n )\n initial_state = grain_dataloader._create_initial_state()\n grain_iterator = grain.DataLoaderIterator(grain_dataloader, initial_state)\n\n # --- Restore checkpoint ---\n if args.restore_ckpt:\n abstract_optimizer = nnx.eval_shape(lambda: optimizer)\n abstract_optimizer_state = nnx.state(abstract_optimizer)\n restored = checkpoint_manager.restore(\n checkpoint_manager.latest_step(),\n args=ocp.args.Composite(\n model_state=ocp.args.PyTreeRestore(abstract_optimizer_state), # type: ignore\n dataloader_state=grain.checkpoint.CheckpointRestore(grain_iterator), # type: ignore\n ),\n )\n restored_optimizer_state = restored[""model_state""]\n nnx.update(optimizer, restored_optimizer_state)\n grain_iterator = restored[""dataloader_state""]\n step = checkpoint_manager.latest_step() or 0\n print(f""Restored dataloader and model state from step {step}"")\n else:\n # Restore from pre-trained tokenizer (and LAM)\n optimizer = restore_genie_components(optimizer, replicated_sharding, rng, args)\n # NOTE: We have to remove the (unused) tokenizer vq dropout due flax.nnx lazily initializing modules.\n # Specifically, the first dynamics model checkpoint will contain the vq dropout module,\n # but the first full restore will fail due to nnx not initializing the module when\n # dropout is set to 0.0.\n del optimizer.model.tokenizer.vq.drop\n\n # --- TRAIN LOOP ---\n # dataloader = (\n # jax.make_array_from_process_local_data(videos_sharding, elem)\n # for elem in grain_iterator\n # )\n jax.config.update(""jax_transfer_guard"", ""disallow"")\n print(f""Starting training from step {step}..."")\n should_break = False\n while step < args.num_steps and not should_break:\n for _ in range(5):\n # --- Train step ---\n rng, _rng_mask = jax.random.split(rng, 2)\n inputs = dict(mask_rng=_rng_mask)\n loss, recon, metrics = train_step(optimizer.model, optimizer, inputs)\n metrics[""lr""] = lr_schedule(step)\n print(f""Step {step}, loss: {loss}"")\n step += 1\n\n # --- Logging ---\n if args.log:\n if step % args.log_interval == 0 and jax.process_index() == 0:\n wandb.log(\n {\n ""loss"": loss,\n ""step"": step,\n **metrics,\n }\n )\n if step % args.log_image_interval == 0:\n pass\n # gt_seq = inputs[""videos""][0].astype(jnp.float32) / 255.0\n # recon_seq = recon[0].clip(0, 1)\n # comparison_seq = jnp.concatenate((gt_seq, recon_seq), axis=1)\n # comparison_seq = einops.rearrange(\n # comparison_seq * 255, ""t h w c -> h (t w) c""\n # )\n # if jax.process_index() == 0:\n # log_images = dict(\n # image=wandb.Image(np.asarray(gt_seq[args.seq_len - 1])),\n # recon=wandb.Image(np.asarray(recon_seq[args.seq_len - 1])),\n # true_vs_recon=wandb.Image(\n # np.asarray(comparison_seq.astype(np.uint8))\n # ),\n # )\n # wandb.log(log_images)\n # --- Checkpointing ---\n if args.save_ckpt and step % args.log_checkpoint_interval == 0:\n optimizer_state = nnx.state(optimizer)\n checkpoint_manager.save(\n step,\n args=ocp.args.Composite(\n model_state=ocp.args.PyTreeSave(optimizer_state), # type: ignore\n dataloader_state=grain.checkpoint.CheckpointSave( # type: ignore\n grain_iterator # type: ignore\n ),\n ),\n )\n print(f""Saved checkpoint at step {step}"")\n if step >= 5:\n should_break = True\n break\n\n checkpoint_manager.close()\n",python,tab
|
| 3 |
+
2,715,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"9:12:59 AM [info] Activating crowd-code\n9:12:59 AM [info] Recording started\n9:12:59 AM [info] Initializing git provider using file system watchers...\n",Log,tab
|
| 4 |
+
3,839,"extension-output-pdoom-org.crowd-code-#1-crowd-code",150,0,"9:12:59 AM [info] Git repository found\n9:13:00 AM [info] Git provider initialized successfully\n9:13:00 AM [info] Initial git state: [object Object]\n",Log,content
|
| 5 |
+
4,5303891,"train_dynamics.py",0,0,"",python,tab
|
| 6 |
+
5,5307144,"utils/nn.py",0,0,"import math\nfrom typing import Tuple, Callable, List\n\nfrom flax import nnx\nimport jax\nimport jax.numpy as jnp\nimport einops\n\n\nclass SpatioTemporalPositionalEncoding(nnx.Module):\n """"""\n Applies separate sinusoidal positional encodings to the temporal and spatial dimensions.\n """"""\n def __init__(self, d_model: int, max_len: int = 5000):\n self.d_model = d_model\n self.max_len = max_len\n\n pe = jnp.zeros((self.max_len, self.d_model))\n position = jnp.arange(0, self.max_len, dtype=jnp.float32)[:, None]\n div_term = jnp.exp(\n jnp.arange(0, self.d_model, 2) * (-math.log(10000.0) / self.d_model)\n )\n pe = pe.at[:, 0::2].set(jnp.sin(position * div_term))\n pe = pe.at[:, 1::2].set(jnp.cos(position * div_term))\n self.pe = nnx.Variable(pe)\n\n def __call__(self, x: jax.Array) -> jax.Array:\n """"""\n Args:\n x: The input tensor of shape (Batch, Time, Space, Dimension).\n\n Returns:\n The input tensor with positional encodings added.\n """"""\n assert x.ndim == 4, f""Input must be 4-dimensional, but got shape {x.shape}""\n\n num_timesteps = x.shape[1]\n num_spatial_patches = x.shape[2]\n\n # Temporal positional encoding: (1, T, 1, D)\n temporal_pe = self.pe.value[None, :num_timesteps, None, :]\n x = x + temporal_pe\n\n # Spatial positional encoding: (1, 1, S, D)\n spatial_pe = self.pe.value[None, None, :num_spatial_patches, :]\n x = x + spatial_pe\n\n return x\n\n\nclass STBlock(nnx.Module):\n def __init__(\n self,\n dim: int,\n ffn_dim: int,\n num_heads: int,\n dropout: float,\n param_dtype: jnp.dtype,\n dtype: jnp.dtype,\n use_flash_attention: bool,\n rngs: nnx.Rngs,\n ):\n self.dim = dim\n self.ffn_dim = ffn_dim\n self.num_heads = num_heads\n self.dropout = dropout\n self.param_dtype = param_dtype\n self.dtype = dtype\n self.use_flash_attention = use_flash_attention\n\n self.spatial_norm = nnx.LayerNorm(\n num_features=self.dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n self.spatial_attention = nnx.MultiHeadAttention(\n num_heads=self.num_heads,\n in_features=self.dim,\n qkv_features=self.dim,\n dropout_rate=self.dropout,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n attention_fn=_create_flash_attention_fn(\n self.use_flash_attention, is_causal=False\n ),\n rngs=rngs,\n decode=False,\n )\n\n self.temporal_norm = nnx.LayerNorm(\n num_features=self.dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n self.temporal_attention = nnx.MultiHeadAttention(\n num_heads=self.num_heads,\n in_features=self.dim,\n qkv_features=self.dim,\n dropout_rate=self.dropout,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n attention_fn=_create_flash_attention_fn(\n self.use_flash_attention, is_causal=True\n ),\n rngs=rngs,\n decode=False,\n )\n\n self.ffn_norm = nnx.LayerNorm(\n num_features=self.dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n self.ffn_dense1 = nnx.Linear(\n in_features=self.dim,\n out_features=self.ffn_dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n self.ffn_dense2 = nnx.Linear(\n in_features=self.ffn_dim,\n out_features=self.dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n\n @nnx.remat\n def __call__(self, x_BTNM: jax.Array) -> jax.Array:\n # --- Spatial attention ---\n z_BTNM = self.spatial_norm(x_BTNM)\n z_BTNM = self.spatial_attention(z_BTNM)\n x_BTNM = x_BTNM + z_BTNM\n\n # --- Temporal attention ---\n x_BNTM = x_BTNM.swapaxes(1, 2)\n z_BNTM = self.temporal_norm(x_BNTM)\n z_BNTM = self.temporal_attention(z_BNTM)\n x_BNTM = x_BNTM + z_BNTM\n x_BTNM = x_BNTM.swapaxes(1, 2)\n\n # --- Feedforward ---\n z_BTNM = self.ffn_norm(x_BTNM)\n z_BTND = self.ffn_dense1(z_BTNM)\n z_BTND = jax.nn.gelu(z_BTND)\n z_BTNM = self.ffn_dense2(z_BTND)\n x_BTNM = x_BTNM + z_BTNM\n\n return x_BTNM\n\n\nclass STTransformer(nnx.Module):\n """"""\n Dimension keys:\n B: batch size\n T: number of frames\n N: number of patches per frame\n I: number of input features\n M: model dimension\n D: FFN dimension\n O: number of output features\n """"""\n def __init__(\n self,\n input_dim: int,\n model_dim: int,\n ffn_dim: int,\n out_dim: int,\n num_blocks: int,\n num_heads: int,\n dropout: float,\n param_dtype: jnp.dtype,\n dtype: jnp.dtype,\n use_flash_attention: bool,\n rngs: nnx.Rngs,\n max_len: int = 5000,\n ):\n self.input_dim = input_dim\n self.model_dim = model_dim\n self.ffn_dim = ffn_dim\n self.out_dim = out_dim\n self.num_blocks = num_blocks\n self.num_heads = num_heads\n self.dropout = dropout\n self.param_dtype = param_dtype\n self.dtype = dtype\n self.use_flash_attention = use_flash_attention\n\n self.input_norm1 = nnx.LayerNorm(\n num_features=self.input_dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n self.input_dense = nnx.Linear(\n in_features=self.input_dim,\n out_features=self.model_dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n self.input_norm2 = nnx.LayerNorm(\n num_features=self.model_dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n\n self.pos_enc = SpatioTemporalPositionalEncoding(self.model_dim, max_len=max_len)\n\n self.blocks = []\n for _ in range(self.num_blocks):\n self.blocks.append(\n STBlock(\n dim=self.model_dim,\n ffn_dim=self.ffn_dim,\n num_heads=self.num_heads,\n dropout=self.dropout,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n use_flash_attention=self.use_flash_attention,\n rngs=rngs,\n )\n )\n\n self.output_dense = nnx.Linear(\n in_features=self.model_dim,\n out_features=self.out_dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n\n def __call__(self, x_BTNI: jax.Array) -> jax.Array:\n x_BTNI = self.input_norm1(x_BTNI)\n x_BTNM = self.input_dense(x_BTNI)\n x_BTNM = self.input_norm2(x_BTNM)\n x_BTNM = self.pos_enc(x_BTNM)\n for block in self.blocks:\n x_BTNM = block(x_BTNM)\n\n x_BTNO = self.output_dense(x_BTNM)\n return x_BTNO\n\nclass TransformerBlock(nnx.Module):\n def __init__(\n self,\n model_dim: int,\n ffn_dim: int,\n num_heads: int,\n dropout: float,\n param_dtype: jnp.dtype,\n dtype: jnp.dtype,\n use_flash_attention: bool,\n decode: bool,\n rngs: nnx.Rngs,\n ):\n self.model_dim = model_dim\n self.ffn_dim = ffn_dim\n self.num_heads = num_heads\n self.dropout = dropout\n self.param_dtype = param_dtype\n self.dtype = dtype\n self.use_flash_attention = use_flash_attention\n self.decode = decode\n\n self.temporal_norm = nnx.LayerNorm(\n num_features=self.model_dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n self.spatial_norm = nnx.LayerNorm(\n num_features=self.model_dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n self.ffn_norm = nnx.LayerNorm(\n num_features=self.model_dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n self.temporal_attention = nnx.MultiHeadAttention(\n num_heads=self.num_heads,\n in_features=self.model_dim,\n qkv_features=self.model_dim,\n dropout_rate=self.dropout,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n attention_fn=_create_flash_attention_fn(\n self.use_flash_attention, is_causal=True\n ),\n rngs=rngs,\n decode=self.decode,\n )\n self.spatial_attention = nnx.MultiHeadAttention(\n num_heads=self.num_heads,\n in_features=self.model_dim,\n qkv_features=self.model_dim,\n dropout_rate=self.dropout,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n attention_fn=_create_flash_attention_fn(\n self.use_flash_attention, is_causal=True\n ),\n rngs=rngs,\n decode=self.decode,\n )\n self.ffn_dense1 = nnx.Linear(\n in_features=self.model_dim,\n out_features=self.ffn_dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n self.ffn_dense2 = nnx.Linear(\n in_features=self.ffn_dim,\n out_features=self.model_dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n\n @nnx.remat\n def __call__(self, x_BTNM: jax.Array, pos_index: Tuple[jax.Array, jax.Array] | None = None) -> jax.Array:\n # --- Spatial attention ---\n B, T, N, M = x_BTNM.shape\n z_FNM = einops.rearrange(x_BTNM, ""b t n m -> (b t) n m"")\n z_FNM = self.spatial_norm(z_FNM)\n z_FNM = self.spatial_attention(z_FNM)\n z_BTNM = einops.rearrange(z_FNM, ""(b t) n m -> b t n m"", t=T)\n x_BTNM = x_BTNM + z_BTNM\n # --- Temporal attention ---\n z_PTM = einops.rearrange(x_BTNM, ""b t n m -> (b n) t m"")\n z_PTM = self.temporal_norm(z_PTM)\n z_PTM = self.temporal_attention(z_PTM)\n z_BTNM = einops.rearrange(z_PTM, ""(b n) t m -> b t n m"", n=N)\n x_BTNM = x_BTNM + z_BTNM\n # --- Feedforward ---\n z_BTNM = self.ffn_norm(x_BTNM)\n z_BTND = self.ffn_dense1(z_BTNM)\n z_BTND = jax.nn.gelu(z_BTND)\n z_BTNM = self.ffn_dense2(z_BTND)\n x_BTNM = x_BTNM + z_BTNM\n\n return x_BTNM\n\nclass Transformer(nnx.Module):\n """"""\n Dimension keys:\n B: batch size\n T: number of frames\n N: number of patches per frame\n I: number of input features\n M: model dimension\n D: FFN dimension\n O: number of output features\n F: number of frames in batch\n P: number of patch positions in batch\n """"""\n def __init__(\n self,\n input_dim: int,\n model_dim: int,\n ffn_dim: int,\n out_dim: int,\n num_blocks: int,\n num_heads: int,\n dropout: float,\n param_dtype: jnp.dtype,\n dtype: jnp.dtype,\n use_flash_attention: bool,\n decode: bool,\n rngs: nnx.Rngs,\n max_len: int = 5000,\n ):\n self.input_dim = input_dim\n self.model_dim = model_dim\n self.ffn_dim = ffn_dim\n self.out_dim = out_dim\n self.num_blocks = num_blocks\n self.num_heads = num_heads\n self.dropout = dropout\n self.param_dtype = param_dtype\n self.dtype = dtype\n self.use_flash_attention = use_flash_attention\n\n self.input_norm1 = nnx.LayerNorm(\n num_features=self.input_dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n self.input_dense = nnx.Linear(\n in_features=self.input_dim,\n out_features=self.model_dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n self.input_norm2 = nnx.LayerNorm(\n num_features=self.model_dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n\n self.pos_enc = SpatioTemporalPositionalEncoding(self.model_dim, max_len=max_len)\n\n self.blocks: List[TransformerBlock] = []\n for _ in range(self.num_blocks):\n self.blocks.append(\n TransformerBlock(\n model_dim=self.model_dim,\n ffn_dim=self.ffn_dim,\n num_heads=self.num_heads,\n dropout=self.dropout,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n use_flash_attention=self.use_flash_attention,\n decode=decode,\n rngs=rngs,\n )\n )\n self.output_dense = nnx.Linear(\n in_features=self.model_dim,\n out_features=self.out_dim,\n param_dtype=self.param_dtype,\n dtype=self.dtype,\n rngs=rngs,\n )\n\n def __call__(self, x_BTNI: jax.Array, pos_index: Tuple[jax.Array, jax.Array] | None = None) -> jax.Array:\n x_BTNI = self.input_norm1(x_BTNI)\n x_BTNM = self.input_dense(x_BTNI)\n x_BTNM = self.input_norm2(x_BTNM)\n x_BTNM = self.pos_enc(x_BTNM)\n for block in self.blocks:\n x_BTNM = block(x_BTNM, pos_index)\n\n x_BTNV = self.output_dense(x_BTNM)\n return x_BTNV\n\ndef normalize(x: jax.Array) -> jax.Array:\n return x / (jnp.linalg.norm(x, ord=2, axis=-1, keepdims=True) + 1e-8)\n\n\nclass VectorQuantizer(nnx.Module):\n """"""\n Dimension keys:\n D: B * T * N\n K: number of latents\n L: latent dimension\n """"""\n def __init__(\n self, latent_dim: int, num_latents: int, dropout: float, rngs: nnx.Rngs\n ):\n self.latent_dim = latent_dim\n self.num_latents = num_latents\n self.dropout = dropout\n\n self.codebook = nnx.Param(\n normalize(\n nnx.initializers.lecun_uniform()(\n rngs.params(), (self.num_latents, self.latent_dim)\n )\n )\n )\n self.drop = nnx.Dropout(self.dropout, rngs=rngs)\n\n def __call__(\n self, x_DL: jax.Array, training: bool\n ) -> Tuple[jax.Array, jax.Array, jax.Array, jax.Array]:\n # --- Compute distances ---\n x_DL = normalize(x_DL)\n normalized_codebook_KL = normalize(self.codebook.value)\n distance_DK = -jnp.matmul(x_DL, normalized_codebook_KL.T)\n if training:\n distance_DK = self.drop(distance_DK)\n\n # --- Get indices and embeddings ---\n indices_D = jnp.argmin(distance_DK, axis=-1)\n z_DL = self.codebook[indices_D]\n\n # --- Straight through estimator ---\n z_q_DL = x_DL + jax.lax.stop_gradient(z_DL - x_DL)\n return z_q_DL, z_DL, x_DL, indices_D\n\n def get_codes(self, indices_E: jax.Array) -> jax.Array:\n return self.codebook[indices_E]\n\n\ndef _create_flash_attention_fn(use_flash_attention: bool, is_causal: bool) -> Callable:\n """"""\n Create an attention function that uses flash attention if enabled.\n\n flax.nnx.MultiHeadAttention provides tensors with shape (batch..., length, num_heads, head_dim),\n but jax.nn.dot_product_attention expects (batch, length, num_heads, head_dim). We reshape to\n ensure compatibility. cuDNN's flash attention additionally requires a sequence length that\n is a multiple of 4. We pad the sequence length to the nearest multiple of 4 and mask\n accordingly. Note that cuDNN requires the mask to be broadcast before calling the attention\n function due to strict shape checking.\n """"""\n\n def attention_fn(query_BTHD, key_BSHD, value_BSHD, bias=None, mask_B111=None, **kwargs):\n implementation = ""cudnn"" if use_flash_attention else None\n\n def _merge_batch_dims(x):\n return einops.rearrange(x, ""... l h k -> (...) l h k"")\n\n def _pad(x, pad_size):\n return jnp.pad(x, ((0, 0), (0, pad_size), (0, 0), (0, 0)))\n\n original_shape = query_BTHD.shape\n T = query_BTHD.shape[-3]\n S = key_BSHD.shape[-3]\n\n # Pad to nearest multiple of 4\n Q = ((T + 3) // 4) * 4\n pad_size_Q = Q - T\n K = ((S + 3) // 4) * 4\n pad_size_K = K - S\n\n query_BQHD = _pad(_merge_batch_dims(query_BTHD), pad_size_Q)\n key_BKHD = _pad(_merge_batch_dims(key_BSHD), pad_size_K)\n value_BKHD = _pad(_merge_batch_dims(value_BSHD), pad_size_K)\n\n attention_mask = jnp.ones((Q, K), dtype=jnp.bool_)\n attention_mask = attention_mask.at[T:, :].set(False)\n attention_mask = attention_mask.at[:, S:].set(False)\n\n mask_11TS = attention_mask[jnp.newaxis, jnp.newaxis, :, :]\n\n bias_4d = jnp.pad(_merge_batch_dims(bias), ((0, 0), (0, 0), (0, pad_size_Q), (0, pad_size_K))) if bias is not None else None\n\n # NOTE: jax.nn.dot_product_attention does not support dropout\n output_4d = jax.nn.dot_product_attention(\n query=query_BQHD,\n key=key_BKHD,\n value=value_BKHD,\n bias=bias_4d,\n mask=mask_11TS,\n implementation=implementation,\n is_causal=is_causal,\n )\n return output_4d[..., :T, :, :].reshape(original_shape)\n\n return attention_fn\n",python,tab
|
| 7 |
+
6,5308049,"utils/nn.py",3964,0,"",python,selection_command
|
| 8 |
+
7,5613392,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"",Log,tab
|
| 9 |
+
8,5615591,"utils/nn.py",0,0,"",python,tab
|
| 10 |
+
9,5615594,"TERMINAL",0,0,"",,terminal_focus
|
| 11 |
+
10,5616949,"TERMINAL",0,0,"source /home/franz.srambical/jafar/.venv/bin/activate",,terminal_command
|
| 12 |
+
11,5618993,"TERMINAL",0,0,"squeue",,terminal_command
|
| 13 |
+
12,5619013,"TERMINAL",0,0,"]633;C JOBID USER PARTITION NODES CPUS ST SUBMIT_TIME START_TIME TIME TIME_LIMIT NODELIST(REASON)\r\n 20041 xiao.liu interacti 1 32 R 2025-08-17T05:58:00 2025-08-17T05:58:00 4:48:38 23:59:00 hai004\r\n 20040 xiao.liu interacti 1 32 R 2025-08-17T05:57:42 2025-08-17T05:57:42 4:48:56 23:59:00 hai003\r\n 20015 nishant.ku standard 3 192 R 2025-08-16T15:10:37 2025-08-16T15:10:37 19:36:01 1-00:00:00 hai[001-002,005]\r\n]0;franz.srambical@hai-login2:~/jafar",,terminal_output
|
| 14 |
+
13,5635826,"TERMINAL",0,0,"salloc --gpus=1 --ntasks-per-node=1 --cpus-per-task=1 --mem=100G",,terminal_command
|
| 15 |
+
14,5635881,"TERMINAL",0,0,"]633;Csalloc: Granted job allocation 20042\r\n",,terminal_output
|
| 16 |
+
15,5635977,"TERMINAL",0,0,"salloc: Nodes hai006 are ready for job\r\n",,terminal_output
|
| 17 |
+
16,5636388,"TERMINAL",0,0,"Running inside SLURM, Job ID 20042.\r\n",,terminal_output
|
| 18 |
+
17,5636466,"TERMINAL",0,0,"]0;franz.srambical@hai-login2:~/jafar[?2004h[franz.srambical@hai006.haicore.berlin:~/jafar] $ ",,terminal_output
|
| 19 |
+
18,5648733,"experiments/dynamics_grain_tok_restore.sh",0,0,"#!/usr/bin/env bash\n\n#SBATCH --nodes=2\n#SBATCH --ntasks-per-node=8\n#SBATCH --time=12:00:00\n#SBATCH --cpus-per-task=1\n#SBATCH --gres=gpu:8\n#SBATCH --mem=100GB\n\nsource .venv/bin/activate\n\ndata_dir=""${PWD}/data_arrayrecord/dummy""\nckpt_dir=""${PWD}/checkpoints/causal_dynamics_openai_grain_tok_restore""\ntokenizer_ckpt_dir=""${PWD}/checkpoints/tokenizer_openai_grain_checkpointing""\n\nexport XLA_FLAGS=--xla_gpu_autotune_level=0\nexport PYTHONUNBUFFERED=1\nsrun python train_dynamics.py \\n --dyna_type 'causal' \\n --log_checkpoint_interval 5 \\n --batch_size 12 \\n --tokenizer_checkpoint $tokenizer_ckpt_dir \\n --ckpt_dir $ckpt_dir \\n --num_steps 300000 \\n --warmup_steps 10000 \\n --seed 0 \\n --init_lr=0.0000866 \\n --max_lr=0.0000866 \\n --data_dir $data_dir",shellscript,tab
|
| 20 |
+
19,5649358,"TERMINAL",0,0,"\r(reverse-i-search)`': [K",,terminal_output
|
| 21 |
+
20,5650478,"TERMINAL",0,0,"b': source /home/franz.srambical/jafar/.venv/[7mb[27min/activate",,terminal_output
|
| 22 |
+
21,5650800,"TERMINAL",0,0,"\r[Cfailed reverse-i-search)`bå': source /home/franz.srambical/jafar/.venv/bin/activate\r[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[1@h[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C",,terminal_output
|
| 23 |
+
22,5652492,"TERMINAL",0,0,"\r[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[1P[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C",,terminal_output
|
| 24 |
+
23,5652647,"TERMINAL",0,0,"\r[C[16Preverse-i-search)`b': cd ../s[7mb[27match-runner/coinrun-dynamics-lr-3e-4/\r[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C",,terminal_output
|
| 25 |
+
24,5653291,"TERMINAL",0,0,"a': cd ../s[7mba[27mtch-runner/coinrun-dynamics-lr-3e-4/\r[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[Cs': [7mbas[27mh slurm/utils/create_dev_dir.sh . ../sbatch-runner/coinrun-dynamics-lr-3e-4\r[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[1@h': [7mbash[27m\r[C[8@failed reverse-i-search)`bashh': bash",,terminal_output
|
| 26 |
+
25,5654407,"TERMINAL",0,0,"\r[C[39Preverse-i-search)`bash': [7mbash[27m experiments/dynamics_grain_tok_restore.sh \r[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C[C",,terminal_output
|
| 27 |
+
26,5657413,"experiments/dynamics_grain_tok_restore.sh",375,0,"",shellscript,selection_command
|
| 28 |
+
27,5657479,"experiments/dynamics_grain_tok_restore.sh",759,0,"",shellscript,selection_command
|
| 29 |
+
28,5677161,"experiments/dynamics_grain_tok_restore.sh",734,0,"",shellscript,selection_command
|
| 30 |
+
29,5677410,"experiments/dynamics_grain_tok_restore.sh",708,0,"",shellscript,selection_command
|
| 31 |
+
30,5677440,"experiments/dynamics_grain_tok_restore.sh",693,0,"",shellscript,selection_command
|
| 32 |
+
31,5677470,"experiments/dynamics_grain_tok_restore.sh",666,0,"",shellscript,selection_command
|
| 33 |
+
32,5677505,"experiments/dynamics_grain_tok_restore.sh",641,0,"",shellscript,selection_command
|
| 34 |
+
33,5677540,"experiments/dynamics_grain_tok_restore.sh",614,0,"",shellscript,selection_command
|
| 35 |
+
34,5677571,"experiments/dynamics_grain_tok_restore.sh",565,0,"",shellscript,selection_command
|
| 36 |
+
35,5677602,"experiments/dynamics_grain_tok_restore.sh",543,0,"",shellscript,selection_command
|
| 37 |
+
36,5677637,"experiments/dynamics_grain_tok_restore.sh",509,0,"",shellscript,selection_command
|
| 38 |
+
37,5677667,"experiments/dynamics_grain_tok_restore.sh",482,0,"",shellscript,selection_command
|
| 39 |
+
38,5677703,"experiments/dynamics_grain_tok_restore.sh",450,0,"",shellscript,selection_command
|
| 40 |
+
39,5677734,"experiments/dynamics_grain_tok_restore.sh",424,0,"",shellscript,selection_command
|
| 41 |
+
40,5677769,"experiments/dynamics_grain_tok_restore.sh",380,0,"",shellscript,selection_command
|
| 42 |
+
41,5677804,"experiments/dynamics_grain_tok_restore.sh",375,0,"",shellscript,selection_command
|
| 43 |
+
42,5677834,"experiments/dynamics_grain_tok_restore.sh",302,0,"",shellscript,selection_command
|
| 44 |
+
43,5677869,"experiments/dynamics_grain_tok_restore.sh",231,0,"",shellscript,selection_command
|
| 45 |
+
44,5677904,"experiments/dynamics_grain_tok_restore.sh",190,0,"",shellscript,selection_command
|
| 46 |
+
45,5678460,"experiments/dynamics_grain_tok_restore.sh",186,0,"",shellscript,selection_command
|
| 47 |
+
46,5679007,"experiments/dynamics_grain_tok_restore.sh",227,0,"",shellscript,selection_command
|
| 48 |
+
47,5679242,"experiments/dynamics_grain_tok_restore.sh",298,0,"",shellscript,selection_command
|
| 49 |
+
48,5679277,"experiments/dynamics_grain_tok_restore.sh",375,0,"",shellscript,selection_command
|
| 50 |
+
49,5679305,"experiments/dynamics_grain_tok_restore.sh",376,0,"",shellscript,selection_command
|
| 51 |
+
50,5679337,"experiments/dynamics_grain_tok_restore.sh",420,0,"",shellscript,selection_command
|
| 52 |
+
51,5679367,"experiments/dynamics_grain_tok_restore.sh",446,0,"",shellscript,selection_command
|
| 53 |
+
52,5679402,"experiments/dynamics_grain_tok_restore.sh",478,0,"",shellscript,selection_command
|
| 54 |
+
53,5679432,"experiments/dynamics_grain_tok_restore.sh",505,0,"",shellscript,selection_command
|
| 55 |
+
54,5694374,"experiments/dynamics_grain_tok_restore.sh",539,0,"",shellscript,selection_command
|
| 56 |
+
55,5699129,"/fast/home/franz.srambical/jafar/.venv/lib/python3.10/site-packages/orbax/checkpoint/_src/asyncio_utils.py",0,0,"# Copyright 2025 The Orbax Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the ""License"");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an ""AS IS"" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n""""""Provides helper async functions.""""""\n\nimport asyncio\nimport functools\nfrom typing import Any, Coroutine, TypeVar\nimport nest_asyncio\n\n\n_T = TypeVar('_T')\n\n\ndef as_async_function(func):\n """"""Wraps a function to make it async.""""""\n\n @functools.wraps(func)\n async def run(*args, loop=None, executor=None, **kwargs):\n if loop is None:\n loop = asyncio.get_event_loop()\n partial_func = functools.partial(func, *args, **kwargs)\n return await loop.run_in_executor(executor, partial_func)\n\n return run\n\n\ndef run_sync(\n coro: Coroutine[Any, Any, _T],\n enable_nest_asyncio: bool = True, # For testing.\n) -> _T:\n """"""Runs a coroutine and returns the result.""""""\n try:\n asyncio.get_running_loop() # no event loop: ~0.001s, otherwise: ~0.182s\n if enable_nest_asyncio:\n nest_asyncio.apply() # patch asyncio globally in a runtime (idempotent).\n except RuntimeError:\n pass\n return asyncio.run(coro)\n",python,tab
|
| 57 |
+
56,5700176,"experiments/dynamics_grain_tok_restore.sh",0,0,"",shellscript,tab
|
| 58 |
+
57,5703453,"utils/nn.py",0,0,"",python,tab
|
| 59 |
+
58,5705447,"utils/nn.py",10013,0,"",python,selection_command
|
| 60 |
+
59,5707067,"utils/nn.py",10008,0,"",python,selection_command
|
| 61 |
+
60,5707614,"utils/nn.py",10008,0,"/",python,content
|
| 62 |
+
61,5707614,"utils/nn.py",10009,0,"",python,selection_keyboard
|
| 63 |
+
62,5707739,"utils/nn.py",10009,0,"/",python,content
|
| 64 |
+
63,5707739,"utils/nn.py",10010,0,"",python,selection_keyboard
|
| 65 |
+
64,5707969,"utils/nn.py",10009,0,"",python,selection_command
|
| 66 |
+
65,5709824,"utils/nn.py",10010,0,"# ",python,content
|
| 67 |
+
66,5709824,"utils/nn.py",10008,2,"",python,content
|
| 68 |
+
67,5710647,"utils/nn.py",10010,0,"",python,selection_command
|
| 69 |
+
68,5715687,"train_dynamics.py",0,0,"",python,tab
|
| 70 |
+
69,5732272,"train_dynamics.py",8178,0,"",python,selection_command
|
| 71 |
+
70,5732280,"train_dynamics.py",8177,0,"",python,selection_command
|
| 72 |
+
71,5732491,"train_dynamics.py",8114,0,"",python,selection_command
|
| 73 |
+
72,5732691,"train_dynamics.py",8057,0,"",python,selection_command
|
| 74 |
+
73,5732995,"train_dynamics.py",8114,0,"",python,selection_command
|
| 75 |
+
74,5734092,"train_dynamics.py",8177,0,"",python,selection_command
|
| 76 |
+
75,5734153,"train_dynamics.py",8178,0,"",python,selection_command
|
| 77 |
+
76,5734297,"train_dynamics.py",8241,0,"",python,selection_command
|
| 78 |
+
77,5734373,"train_dynamics.py",8178,0,"",python,selection_command
|
| 79 |
+
78,5734522,"train_dynamics.py",8177,0,"",python,selection_command
|
| 80 |
+
79,5734675,"train_dynamics.py",8114,0,"",python,selection_command
|
| 81 |
+
80,5739207,"train_dynamics.py",8057,0,"",python,selection_command
|
| 82 |
+
81,5739221,"train_dynamics.py",7975,0,"",python,selection_command
|
| 83 |
+
82,5739373,"train_dynamics.py",7974,0,"",python,selection_command
|
| 84 |
+
83,5739506,"train_dynamics.py",7960,0,"",python,selection_command
|
| 85 |
+
84,5739770,"train_dynamics.py",7919,0,"",python,selection_command
|
| 86 |
+
85,5739790,"train_dynamics.py",7913,0,"",python,selection_command
|
| 87 |
+
86,5739820,"train_dynamics.py",7884,0,"",python,selection_command
|
| 88 |
+
87,5739855,"train_dynamics.py",7857,0,"",python,selection_command
|
| 89 |
+
88,5739894,"train_dynamics.py",7841,0,"",python,selection_command
|
| 90 |
+
89,5739922,"train_dynamics.py",7825,0,"",python,selection_command
|
| 91 |
+
90,5741255,"train_dynamics.py",7790,0,"",python,selection_command
|
| 92 |
+
91,5741331,"train_dynamics.py",7768,0,"",python,selection_command
|
| 93 |
+
92,5741469,"train_dynamics.py",7762,0,"",python,selection_command
|
| 94 |
+
93,5741591,"train_dynamics.py",7732,0,"",python,selection_command
|
| 95 |
+
94,5741739,"train_dynamics.py",7705,0,"",python,selection_command
|
| 96 |
+
95,5742734,"train_dynamics.py",7732,0,"",python,selection_command
|
| 97 |
+
96,5742779,"train_dynamics.py",7762,0,"",python,selection_command
|
| 98 |
+
97,5743024,"train_dynamics.py",7768,0,"",python,selection_command
|
| 99 |
+
98,5743050,"train_dynamics.py",7790,0,"",python,selection_command
|
| 100 |
+
99,5743085,"train_dynamics.py",7825,0,"",python,selection_command
|
| 101 |
+
100,5743141,"train_dynamics.py",7841,0,"",python,selection_command
|
| 102 |
+
101,5743173,"train_dynamics.py",7857,0,"",python,selection_command
|
| 103 |
+
102,5743183,"train_dynamics.py",7884,0,"",python,selection_command
|
| 104 |
+
103,5743216,"train_dynamics.py",7913,0,"",python,selection_command
|
| 105 |
+
104,5743252,"train_dynamics.py",7919,0,"",python,selection_command
|
| 106 |
+
105,5743285,"train_dynamics.py",7960,0,"",python,selection_command
|
| 107 |
+
106,5743316,"train_dynamics.py",7974,0,"",python,selection_command
|
| 108 |
+
107,5743349,"train_dynamics.py",7975,0,"",python,selection_command
|
| 109 |
+
108,5743574,"train_dynamics.py",7974,0,"",python,selection_command
|
| 110 |
+
109,5743634,"train_dynamics.py",7960,0,"",python,selection_command
|
| 111 |
+
110,5743894,"train_dynamics.py",7919,0,"",python,selection_command
|
| 112 |
+
111,5743932,"train_dynamics.py",7913,0,"",python,selection_command
|
| 113 |
+
112,5743958,"train_dynamics.py",7884,0,"",python,selection_command
|
| 114 |
+
113,5743983,"train_dynamics.py",7857,0,"",python,selection_command
|
| 115 |
+
114,5744026,"train_dynamics.py",7841,0,"",python,selection_command
|
| 116 |
+
115,5744048,"train_dynamics.py",7825,0,"",python,selection_command
|
| 117 |
+
116,5744089,"train_dynamics.py",7790,0,"",python,selection_command
|
| 118 |
+
117,5744114,"train_dynamics.py",7768,0,"",python,selection_command
|
| 119 |
+
118,5744149,"train_dynamics.py",7762,0,"",python,selection_command
|
| 120 |
+
119,5744181,"train_dynamics.py",7732,0,"",python,selection_command
|
| 121 |
+
120,5744362,"train_dynamics.py",7762,0,"",python,selection_command
|
| 122 |
+
121,5744422,"train_dynamics.py",7768,0,"",python,selection_command
|
| 123 |
+
122,5744671,"train_dynamics.py",7790,0,"",python,selection_command
|
| 124 |
+
123,5744704,"train_dynamics.py",7825,0,"",python,selection_command
|
| 125 |
+
124,5744732,"train_dynamics.py",7841,0,"",python,selection_command
|
| 126 |
+
125,5744762,"train_dynamics.py",7857,0,"",python,selection_command
|
| 127 |
+
126,5744800,"train_dynamics.py",7884,0,"",python,selection_command
|
| 128 |
+
127,5744835,"train_dynamics.py",7913,0,"",python,selection_command
|
| 129 |
+
128,5744866,"train_dynamics.py",7919,0,"",python,selection_command
|
| 130 |
+
129,5744901,"train_dynamics.py",7960,0,"",python,selection_command
|
| 131 |
+
130,5744932,"train_dynamics.py",7974,0,"",python,selection_command
|
| 132 |
+
131,5744973,"train_dynamics.py",7975,0,"",python,selection_command
|
| 133 |
+
132,5745099,"train_dynamics.py",7974,0,"",python,selection_command
|
| 134 |
+
133,5745164,"train_dynamics.py",7960,0,"",python,selection_command
|
| 135 |
+
134,5745422,"train_dynamics.py",7919,0,"",python,selection_command
|
| 136 |
+
135,5745452,"train_dynamics.py",7913,0,"",python,selection_command
|
| 137 |
+
136,5745477,"train_dynamics.py",7884,0,"",python,selection_command
|
| 138 |
+
137,5745513,"train_dynamics.py",7857,0,"",python,selection_command
|
| 139 |
+
138,5745547,"train_dynamics.py",7841,0,"",python,selection_command
|
| 140 |
+
139,5745577,"train_dynamics.py",7825,0,"",python,selection_command
|
| 141 |
+
140,5745614,"train_dynamics.py",7790,0,"",python,selection_command
|
| 142 |
+
141,5745642,"train_dynamics.py",7768,0,"",python,selection_command
|
| 143 |
+
142,5745682,"train_dynamics.py",7762,0,"",python,selection_command
|
| 144 |
+
143,5745824,"train_dynamics.py",7768,0,"",python,selection_command
|
| 145 |
+
144,5745902,"train_dynamics.py",7790,0,"",python,selection_command
|
| 146 |
+
145,5746138,"train_dynamics.py",7825,0,"",python,selection_command
|
| 147 |
+
146,5746173,"train_dynamics.py",7841,0,"",python,selection_command
|
| 148 |
+
147,5746204,"train_dynamics.py",7857,0,"",python,selection_command
|
| 149 |
+
148,5746230,"train_dynamics.py",7884,0,"",python,selection_command
|
| 150 |
+
149,5746260,"train_dynamics.py",7913,0,"",python,selection_command
|
| 151 |
+
150,5746294,"train_dynamics.py",7919,0,"",python,selection_command
|
| 152 |
+
151,5746458,"train_dynamics.py",7913,0,"",python,selection_command
|
| 153 |
+
152,5746504,"train_dynamics.py",7884,0,"",python,selection_command
|
| 154 |
+
153,5746759,"train_dynamics.py",7857,0,"",python,selection_command
|
| 155 |
+
154,5746790,"train_dynamics.py",7841,0,"",python,selection_command
|
| 156 |
+
155,5746830,"train_dynamics.py",7825,0,"",python,selection_command
|
| 157 |
+
156,5746855,"train_dynamics.py",7790,0,"",python,selection_command
|
| 158 |
+
157,5746893,"train_dynamics.py",7768,0,"",python,selection_command
|
| 159 |
+
158,5746939,"train_dynamics.py",7762,0,"",python,selection_command
|
| 160 |
+
159,5746957,"train_dynamics.py",7732,0,"",python,selection_command
|
| 161 |
+
160,5746987,"train_dynamics.py",7705,0,"",python,selection_command
|
| 162 |
+
161,5748067,"train_dynamics.py",7732,0,"",python,selection_command
|
| 163 |
+
162,5748101,"train_dynamics.py",7762,0,"",python,selection_command
|
| 164 |
+
163,5748355,"train_dynamics.py",7768,0,"",python,selection_command
|
| 165 |
+
164,5748385,"train_dynamics.py",7790,0,"",python,selection_command
|
| 166 |
+
165,5748421,"train_dynamics.py",7825,0,"",python,selection_command
|
| 167 |
+
166,5752081,"train_dynamics.py",0,0,"",python,selection_command
|
| 168 |
+
167,5760247,"train_dynamics.py",12265,0,"",python,selection_command
|
| 169 |
+
168,5760963,"train_dynamics.py",12224,0,"",python,selection_command
|
| 170 |
+
169,5762000,"train_dynamics.py",12224,0,"# ",python,content
|
| 171 |
+
170,5762173,"train_dynamics.py",12225,0,"",python,selection_command
|
| 172 |
+
171,5762705,"train_dynamics.py",12226,0,"",python,selection_command
|
| 173 |
+
172,5764394,"TERMINAL",0,0,"\r[24@[franz.srambical@hai006.haicore.berlin:~/jafar] $ bash\r\n[?2004l\r",,terminal_output
|
| 174 |
+
173,5771740,"TERMINAL",0,0,"Running on 1 devices.\r\n",,terminal_output
|
| 175 |
+
174,5777738,"TERMINAL",0,0,"Counting all components: ['dynamics', 'lam', 'tokenizer']\r\nParameter counts:\r\n{'dynamics': 26555392, 'lam': 35115232, 'tokenizer': 33750256, 'total': 95420880}\r\n",,terminal_output
|
| 176 |
+
175,5779366,"TERMINAL",0,0,"WARNING:absl:Metadata file does not exist: /home/franz.srambical/jafar/checkpoints/causal_dynamics_openai_grain_tok_restore/000290/_CHECKPOINT_METADATA\r\n",,terminal_output
|
| 177 |
+
176,5779953,"TERMINAL",0,0,"/fast/home/franz.srambical/jafar/.venv/lib/python3.10/site-packages/orbax/checkpoint/_src/serialization/type_handlers.py:1256: UserWarning: Sharding info not provided when restoring. Populating sharding info from sharding file. Please note restoration time will be slightly increased due to reading from file. Note also that this option is unsafe when restoring on a different topology than the checkpoint was saved with.\r\n warnings.warn(\r\n",,terminal_output
|
| 178 |
+
177,5782002,"TERMINAL",0,0,"Starting training from step 0...\r\n",,terminal_output
|
| 179 |
+
178,5787804,"TERMINAL",0,0,"2025-08-17 10:49:27.188096: W external/xla/xla/service/gpu/autotuning/dot_search_space.cc:200] All configs were filtered out because none of them sufficiently match the hints. Maybe the hints set does not contain a good representative set of valid configs?Working around this by using the full hints set instead.\r\n2025-08-17 10:49:27.188670: W external/xla/xla/service/gpu/autotuning/dot_search_space.cc:200] All configs were filtered out because none of them sufficiently match the hints. Maybe the hints set does not contain a good representative set of valid configs?Working around this by using the full hints set instead.\r\n",,terminal_output
|
| 180 |
+
179,5799645,"TERMINAL",0,0,"jax.errors.SimplifiedTraceback: For simplicity, JAX has removed its internal frames from the traceback of the following exception. Set JAX_TRACEBACK_FILTERING=off to include these.\r\n\r\nThe above exception was the direct cause of the following exception:\r\n\r\nTraceback (most recent call last):\r\n File ""/fast/home/franz.srambical/jafar/train_dynamics.py"", line 368, in <module>\r\n metrics[""lr""] = lr_schedule(step)\r\n File ""/fast/home/franz.srambical/jafar/.venv/lib/python3.10/site-packages/optax/schedules/_join.py"", line 41, in schedule\r\n output = schedules[0](step)\r\n File ""/fast/home/franz.srambical/jafar/.venv/lib/python3.10/site-packages/optax/schedules/_schedule.py"", line 143, in schedule\r\n count = jnp.clip(count - transition_begin, 0, transition_steps)\r\njaxlib._jax.XlaRuntimeError: INVALID_ARGUMENT: Disallowed host-to-device transfer: aval=ShapedArray(int32[]), dst_sharding=SingleDeviceSharding(device=CudaDevice(id=0), memory_kind=device)\r\n",,terminal_output
|
| 181 |
+
180,5801428,"TERMINAL",0,0,"srun: error: hai006: task 0: Exited with exit code 1\r\n]0;franz.srambical@hai-login2:~/jafar[?2004h[franz.srambical@hai006.haicore.berlin:~/jafar] $ ",,terminal_output
|
| 182 |
+
181,5830251,"train_dynamics.py",12227,0,"",python,selection_command
|
| 183 |
+
182,5830400,"train_dynamics.py",12227,0,"j",python,content
|
| 184 |
+
183,5830400,"train_dynamics.py",12228,0,"",python,selection_keyboard
|
| 185 |
+
184,5831232,"train_dynamics.py",12227,0,"",python,selection_command
|
| 186 |
+
185,5831441,"train_dynamics.py",12227,1,"",python,content
|
| 187 |
+
186,5833602,"TERMINAL",0,0,"bash experiments/dynamics_grain_tok_restore.sh ",,terminal_output
|
| 188 |
+
187,5833870,"TERMINAL",0,0,"\r\n[?2004l\r",,terminal_output
|
| 189 |
+
188,5839308,"TERMINAL",0,0,"Running on 1 devices.\r\n",,terminal_output
|
| 190 |
+
189,5844847,"TERMINAL",0,0,"Counting all components: ['dynamics', 'lam', 'tokenizer']\r\nParameter counts:\r\n{'dynamics': 26555392, 'lam': 35115232, 'tokenizer': 33750256, 'total': 95420880}\r\n",,terminal_output
|
| 191 |
+
190,5846450,"TERMINAL",0,0,"WARNING:absl:Metadata file does not exist: /home/franz.srambical/jafar/checkpoints/causal_dynamics_openai_grain_tok_restore/000290/_CHECKPOINT_METADATA\r\n",,terminal_output
|
| 192 |
+
191,5847028,"TERMINAL",0,0,"/fast/home/franz.srambical/jafar/.venv/lib/python3.10/site-packages/orbax/checkpoint/_src/serialization/type_handlers.py:1256: UserWarning: Sharding info not provided when restoring. Populating sharding info from sharding file. Please note restoration time will be slightly increased due to reading from file. Note also that this option is unsafe when restoring on a different topology than the checkpoint was saved with.\r\n warnings.warn(\r\n",,terminal_output
|
| 193 |
+
192,5848640,"TERMINAL",0,0,"Starting training from step 0...\r\n",,terminal_output
|
| 194 |
+
193,5854462,"TERMINAL",0,0,"2025-08-17 10:50:33.834374: W external/xla/xla/service/gpu/autotuning/dot_search_space.cc:200] All configs were filtered out because none of them sufficiently match the hints. Maybe the hints set does not contain a good representative set of valid configs?Working around this by using the full hints set instead.\r\n2025-08-17 10:50:33.834889: W external/xla/xla/service/gpu/autotuning/dot_search_space.cc:200] All configs were filtered out because none of them sufficiently match the hints. Maybe the hints set does not contain a good representative set of valid configs?Working around this by using the full hints set instead.\r\n",,terminal_output
|
| 195 |
+
194,5867060,"TERMINAL",0,0,"Step 0, loss: 16.592065811157227\r\n",,terminal_output
|
| 196 |
+
195,5885744,"TERMINAL",0,0,"Step 1, loss: 2.147503982996568e-05\r\n",,terminal_output
|
| 197 |
+
196,5886503,"TERMINAL",0,0,"Step 2, loss: 4.4394266751623945e-07\r\n",,terminal_output
|
| 198 |
+
197,5887535,"TERMINAL",0,0,"Step 3, loss: 3.746240295754433e-08\r\n",,terminal_output
|
| 199 |
+
198,5888147,"TERMINAL",0,0,"Step 4, loss: 5.636502820038913e-09\r\n",,terminal_output
|
| 200 |
+
199,5889272,"TERMINAL",0,0,"]0;franz.srambical@hai-login2:~/jafar[?2004h[franz.srambical@hai006.haicore.berlin:~/jafar] $ ",,terminal_output
|
| 201 |
+
200,9086151,"train_dynamics.py",0,0,"Switched from branch 'main' to 'full-precision-layernorm'",python,git_branch_checkout
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-6addbcf1-e348-4d74-b8dc-f84f47c305b71767631688034-2026_01_05-17.48.14.851/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-722d4ca4-d4cb-461b-8df1-6d561da0c5421759173367911-2025_09_29-21.16.13.607/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-72482fee-a24c-4c9f-bb09-3efbfa32b9fa1765978902238-2025_12_17-14.41.49.56/source.csv
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Sequence,Time,File,RangeOffset,RangeLength,Text,Language,Type
|
| 2 |
+
1,3,"src/extension.ts",0,0,"import * as vscode from 'vscode';\nimport * as http from 'http';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { Buffer } from 'buffer';\nimport { ConversationStateManager, estimateTokens } from '@crowd-pilot/serializer';\n\n// -------------------- Preference Data Collection --------------------\n\ninterface PreferenceSample {\n\ttimestamp: number;\n\tcontext: Array<{ role: string; content: string }>;\n\tcompletion: {\n\t\trawModelOutput: string;\n\t\tparsedAction: Action | null;\n\t\tavgLogprob: number;\n\t};\n\toutcome: 'accepted' | 'rejected' | 'ignored' | null;\n\toutcomeTimestamp: number | null;\n\tmodelName: string;\n}\n\ninterface PendingPreferenceSample {\n\tsample: PreferenceSample;\n\tshownAt: number;\n}\n\nlet pendingPreferenceSample: PendingPreferenceSample | null = null;\n\nfunction getPreferenceLogPath(): string {\n\tconst cfg = getConfig();\n\tif (cfg.preferenceLogPath) {\n\t\treturn cfg.preferenceLogPath;\n\t}\n\tconst workspaceFolders = vscode.workspace.workspaceFolders;\n\tif (workspaceFolders) {\n\t\treturn path.join(workspaceFolders[0].uri.fsPath, '.crowd-pilot-preferences.jsonl');\n\t}\n\tthrow new Error(""No preference log path found."");\n}\n\n/**\n * Log a preference sample to the JSONL file.\n * Each line is a complete JSON object for easy streaming/parsing.\n */\nfunction logPreferenceSample(sample: PreferenceSample): void {\n\tconst cfg = getConfig();\n\tif (!cfg.enablePreferenceLogging) {\n\t\tconsole.log(`[crowd-pilot] Preference logging disabled, skipping sample`);\n\t\treturn;\n\t}\n\n\tconst logPath = getPreferenceLogPath();\n\tconst line = JSON.stringify(sample) + '\n';\n\t\n\tfs.appendFile(logPath, line, (err) => {\n\t\tif (err) {\n\t\t\tconsole.error('[crowd-pilot] Failed to log preference sample:', err);\n\t\t} else {\n\t\t\tconsole.log(`[crowd-pilot] Logged preference sample, outcome: (${sample.outcome})`);\n\t\t}\n\t});\n}\n\n/**\n * Create a new pending preference sample when showing a preview.\n * This captures all context needed for reward model training.\n */\nfunction createPendingPreferenceSample(\n\tconversationMessages: Array<{ role: string; content: string }>,\n\trawModelOutput: string,\n\tparsedAction: Action | null,\n\tavgLogprob: number,\n\tmodelName: string\n): void {\n\tconst sample: PreferenceSample = {\n\t\ttimestamp: Date.now(),\n\t\tcontext: conversationMessages,\n\t\tcompletion: {\n\t\t\trawModelOutput,\n\t\t\tparsedAction,\n\t\t\tavgLogprob,\n\t\t},\n\t\toutcome: null,\n\t\toutcomeTimestamp: null,\n\t\tmodelName,\n\t};\n\n\tpendingPreferenceSample = {\n\t\tsample,\n\t\tshownAt: Date.now(),\n\t};\n}\n\n/**\n * Record the outcome of the current pending sample and log it.\n */\nfunction recordPreferenceOutcome(outcome: 'accepted' | 'rejected' | 'ignored'): void {\n\tif (!pendingPreferenceSample) {\n\t\treturn;\n\t}\n\n\tconst sample = pendingPreferenceSample.sample;\n\tsample.outcome = outcome;\n\tsample.outcomeTimestamp = Date.now();\n\n\tlogPreferenceSample(sample);\n\n\tpendingPreferenceSample = null;\n}\n\n/**\n * Mark any pending sample as ignored (user moved on without explicit accept/reject).\n */\nfunction markPendingAsIgnored(): void {\n\tif (pendingPreferenceSample) {\n\t\trecordPreferenceOutcome('ignored');\n\t}\n}\n\ntype Action =\n| { kind: 'showTextDocument' }\n| { kind: 'setSelections', selections: Array<{ start: [number, number], end: [number, number] }> }\n| { kind: 'editInsert', position: [number, number], text: string }\n| { kind: 'editDelete', range: { start: [number, number], end: [number, number] } }\n| { kind: 'editReplace', range: { start: [number, number], end: [number, number] }, text: string }\n| { kind: 'terminalShow' }\n| { kind: 'terminalSendText', text: string }\n| { kind: 'openFile', filePath: string, selections?: Array<{ start: [number, number], end: [number, number] }> };\n\n// Configuration helper\nfunction getConfig() {\n\tconst config = vscode.workspace.getConfiguration('crowd-pilot');\n\treturn {\n\t\thostname: config.get<string>('hostname', 'hai001'),\n\t\tport: config.get<number>('port', 30000),\n\t\tbasePath: config.get<string>('basePath', '/v1/chat/completions'),\n\t\tmodelName: config.get<string>('modelName', 'qwen/qwen3-8b'),\n\t\tminAvgLogprob: config.get<number>('minAvgLogprob', -1.0),\n\t\tmaxContextTokens: config.get<number>('maxContextTokens', 120000),\n\t\tpreferenceLogPath: config.get<string>('preferenceLogPath', ''),\n\t\tenablePreferenceLogging: config.get<boolean>('enablePreferenceLogging', true),\n\t};\n}\n\n// -------------------- Context Window Management --------------------\n\n/**\n * Truncate conversation messages to fit within the context window.\n * Assumes system prompt is the first message. Drops oldest conversation messages first.\n */\nfunction truncateToContextLimit(\n\tmessages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>,\n\tmaxTokens: number\n): Array<{ role: 'system' | 'user' | 'assistant'; content: string }> {\n\tif (messages.length === 0) { return messages; }\n\n\tconst systemTokens = estimateTokens(messages[0].content);\n\tconst availableTokens = maxTokens - systemTokens;\n\n\tconst tokenCounts = messages.slice(1).map(m => estimateTokens(m.content));\n\tconst totalConversationTokens = tokenCounts.reduce((a, b) => a + b, 0);\n\n\tif (totalConversationTokens <= availableTokens) {\n\t\treturn messages;\n\t}\n\n\tlet keptTokens = 0;\n\tlet cutoffIndex = tokenCounts.length;\n\tfor (let i = tokenCounts.length - 1; i >= 0; i--) {\n\t\tif (keptTokens + tokenCounts[i] <= availableTokens) {\n\t\t\tkeptTokens += tokenCounts[i];\n\t\t\tcutoffIndex = i;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tconsole.log(`[crowd-pilot] Truncated ${cutoffIndex} oldest messages (${systemTokens + totalConversationTokens} -> ${systemTokens + keptTokens} tokens)`);\n\treturn [messages[0], ...messages.slice(cutoffIndex + 1)];\n}\n\n\n// Global conversation state manager instance\nconst conversationManager = new ConversationStateManager();\n\n// Track activated files (files whose content we've captured)\n// TODO (f.srambical): This logic remains on the extension-side\n// for backwards-compatibility (with the crowd-code dataset).\n// Eventually, we should move the file tracking logic to\n// p-doom/crowd-pilot-serializer.\nconst activatedFiles = new Set<string>();\n\n/**\n * Clear all conversation context - resets the conversation manager and activated files.\n * Call this to start fresh without accumulated history.\n */\nfunction clearContext(): void {\n\tconversationManager.reset();\n\tactivatedFiles.clear();\n\tconsole.log('[crowd-pilot] Context cleared');\n}\n\nlet suggestionsEnabled = true;\nlet statusBarItem: vscode.StatusBarItem | undefined;\n\nfunction updateStatusBarItem(): void {\n\tif (!statusBarItem) { return; }\n\tif (suggestionsEnabled) {\n\t\tstatusBarItem.text = '$(lightbulb) crowd-pilot';\n\t\tstatusBarItem.tooltip = 'crowd-pilot: Tab suggestions enabled (click to disable)';\n\t\tstatusBarItem.backgroundColor = undefined;\n\t} else {\n\t\tstatusBarItem.text = '$(lightbulb-autofix) crowd-pilot';\n\t\tstatusBarItem.tooltip = 'crowd-pilot: Tab suggestions disabled (click to enable)';\n\t\tstatusBarItem.backgroundColor = new vscode.ThemeColor('statusBarItem.warningBackground');\n\t}\n}\n\nexport function activate(context: vscode.ExtensionContext) {\n\n\tconsole.log('[crowd-pilot] Extension activated');\n\n\t(async () => {\n\t\tconst config = vscode.workspace.getConfiguration('terminal.integrated');\n\t\tconst commandsToSkipShell = config.get<string[]>('commandsToSkipShell', []);\n\t\tlet updated = false;\n\t\tif (!commandsToSkipShell.includes('crowd-pilot.modelRun')) {\n\t\t\tcommandsToSkipShell.push('crowd-pilot.modelRun');\n\t\t\tupdated = true;\n\t\t}\n\t\tif (!commandsToSkipShell.includes('crowd-pilot.hideUi')) {\n\t\t\tcommandsToSkipShell.push('crowd-pilot.hideUi');\n\t\t\tupdated = true;\n\t\t}\n\t\tif (updated) {\n\t\t\tawait config.update('commandsToSkipShell', commandsToSkipShell, vscode.ConfigurationTarget.Global);\n\t\t}\n\t})().catch((err) => console.error('[crowd-pilot] Startup initialization error:', err));\n\n\tstatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);\n\tstatusBarItem.command = 'crowd-pilot.toggleSuggestions';\n\tupdateStatusBarItem();\n\tstatusBarItem.show();\n\tcontext.subscriptions.push(statusBarItem);\n\n\tconst toggleSuggestions = vscode.commands.registerCommand('crowd-pilot.toggleSuggestions', () => {\n\t\tsuggestionsEnabled = !suggestionsEnabled;\n\t\tupdateStatusBarItem();\n\t\tif (!suggestionsEnabled) {\n\t\t\thidePreviewUI(true);\n\t\t}\n\t\tvscode.window.showInformationMessage(\n\t\t\tsuggestionsEnabled \n\t\t\t\t? '[crowd-pilot]: Tab suggestions enabled' \n\t\t\t\t: '[crowd-pilot]: Tab suggestions disabled'\n\t\t);\n\t});\n\n\tconst hideUi = vscode.commands.registerCommand('crowd-pilot.hideUi', () => {\n\t\trecordPreferenceOutcome('rejected');\n\t\thidePreviewUI(true);\n\t});\n\n\tconst clearContextCmd = vscode.commands.registerCommand('crowd-pilot.clearContext', () => {\n\t\tclearContext();\n\t\tvscode.window.showInformationMessage('[crowd-pilot]: Context cleared');\n\t});\n\n\tconst openPreferenceLogCmd = vscode.commands.registerCommand('crowd-pilot.openPreferenceLog', async () => {\n\t\tconst logPath = getPreferenceLogPath();\n\t\ttry {\n\t\t\tconst uri = vscode.Uri.file(logPath);\n\t\t\tawait vscode.window.showTextDocument(uri);\n\t\t} catch (err: any) {\n\t\t\tif (err.code === 'ENOENT' || err.message?.includes('ENOENT')) {\n\t\t\t\tvscode.window.showInformationMessage('[crowd-pilot] No preference log file exists yet. Accept or reject some suggestions first.');\n\t\t\t} else {\n\t\t\t\tvscode.window.showErrorMessage(`[crowd-pilot] Error opening preference log: ${err.message}`);\n\t\t\t}\n\t\t}\n\t});\n\n\tconst modelRun = vscode.commands.registerCommand('crowd-pilot.modelRun', async () => {\n\t\tconst editor = vscode.window.activeTextEditor;\n\t\tif (!editor) {\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tif (!previewVisible) { return; }\n\t\t\tlet action: Action | undefined = currentAction;\n\t\t\tif (!action) {\n\t\t\t\tconst single = await requestModelActions(editor);\n\t\t\t\tcurrentAction = single;\n\t\t\t\taction = single;\n\t\t\t}\n\t\t\tif (!action) {\n\t\t\t\thidePreviewUI();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\trecordPreferenceOutcome('accepted');\n\t\t\thidePreviewUI(false);\n\t\t\tawait executeAction(action);\n\t\t\tautoShowNextAction();\n\t\t} catch (err) {\n\t\t\tconst errorMessage = err instanceof Error ? err.message : String(err);\n\t\t\tvscode.window.showErrorMessage(`Model run failed: ${errorMessage}`);\n\t\t}\n\t});\n\n\tconst sglangTest = vscode.commands.registerCommand('crowd-pilot.sglangTest', async () => {\n\t\ttry {\n\t\t\tawait callSGLangChat();\n\t\t} catch (err) {\n\t\t\tconst errorMessage = err instanceof Error ? err.message : String(err);\n\t\t\tvscode.window.showErrorMessage(`SGLang test failed: ${errorMessage}`);\n\t\t}\n\t});\n\n\tconst onSelChange = vscode.window.onDidChangeTextEditorSelection((e) => {\n\t\tif (e.textEditor === vscode.window.activeTextEditor) {\n\t\t\tsuppressAutoPreview = false;\n\t\t\tschedulePredictionRefresh(true, false);\n\n\t\t\tconst editor = e.textEditor;\n\t\t\tconst selection = e.selections[0];\n\t\t\tif (selection) {\n\t\t\t\tconst filePath = editor.document.uri.fsPath;\n\t\t\t\tconst offset = editor.document.offsetAt(selection.start);\n\t\t\t\tconversationManager.handleSelectionEvent(filePath, offset);\n\t\t\t}\n\t\t}\n\t});\n\n\tconst onActiveChange = vscode.window.onDidChangeActiveTextEditor((editor) => {\n\t\tsuppressAutoPreview = false;\n\t\tschedulePredictionRefresh(true, false);\n\n\t\tif (editor) {\n\t\t\tconst filePath = editor.document.uri.fsPath;\n\t\t\tconst currentFileUri = editor.document.uri.toString();\n\t\t\tlet tabEventText: string | null = null;\n\n\t\t\tif (!activatedFiles.has(currentFileUri)) {\n\t\t\t\ttabEventText = editor.document.getText();\n\t\t\t\tactivatedFiles.add(currentFileUri);\n\t\t\t}\n\n\t\t\tconversationManager.handleTabEvent(filePath, tabEventText);\n\t\t}\n\t});\n\n\tconst onDocChange = vscode.workspace.onDidChangeTextDocument((e) => {\n\t\tif (vscode.window.activeTextEditor?.document === e.document) {\n\t\t\tsuppressAutoPreview = false;\n\t\t\tschedulePredictionRefresh(true, false);\n\n\t\t\tconst filePath = e.document.uri.fsPath;\n\t\t\tfor (const change of e.contentChanges) {\n\t\t\t\tconst offset = change.rangeOffset;\n\t\t\t\tconst length = change.rangeLength;\n\t\t\t\tconst newText = change.text;\n\t\t\t\tconversationManager.handleContentEvent(filePath, offset, length, newText);\n\t\t\t}\n\t\t}\n\t});\n\n\t// Terminal focus event\n\tconst onTerminalChange = vscode.window.onDidChangeActiveTerminal((terminal) => {\n\t\tif (terminal) {\n\t\t\tconversationManager.handleTerminalFocusEvent();\n\t\t}\n\t});\n\n\t// Terminal command execution event\n\tconst onTerminalCommand = vscode.window.onDidStartTerminalShellExecution(async (event) => {\n\t\tconst commandLine = event.execution.commandLine.value;\n\t\tconversationManager.handleTerminalCommandEvent(commandLine);\n\n\t\t// Capture terminal output\n\t\tconst stream = event.execution.read();\n\t\tfor await (const data of stream) {\n\t\t\tconversationManager.handleTerminalOutputEvent(data);\n\t\t}\n\t});\n\n\tcontext.subscriptions.push(\n\t\ttoggleSuggestions,\n\t\thideUi,\n\t\tclearContextCmd,\n\t\topenPreferenceLogCmd,\n\t\tsglangTest,\n\t\tmodelRun,\n\t\tonSelChange,\n\t\tonActiveChange,\n\t\tonDocChange,\n\t\tonTerminalChange,\n\t\tonTerminalCommand\n\t);\n\n\t// Initialize: capture current active editor if any\n\tconst initialEditor = vscode.window.activeTextEditor;\n\tif (initialEditor) {\n\t\tconst filePath = initialEditor.document.uri.fsPath;\n\t\tconst currentFileUri = initialEditor.document.uri.toString();\n\t\tconst tabEventText = initialEditor.document.getText();\n\t\tactivatedFiles.add(currentFileUri);\n\t\tconversationManager.handleTabEvent(filePath, tabEventText);\n\t}\n}\n\nexport function deactivate() {}\n\n// -------------------- Execution --------------------\nlet currentAction: Action | undefined;\n\nfunction getActiveOrCreateTerminal(): vscode.Terminal {\n\tif (vscode.window.activeTerminal) {\n\t\treturn vscode.window.activeTerminal;\n\t}\n\treturn vscode.window.createTerminal('crowd-pilot');\n}\n\nasync function executeAction(action: Action): Promise<void> {\n\tconst editor = vscode.window.activeTextEditor;\n\tif (!editor) { return; }\n\tconst doc = editor.document;\n\tif (action.kind === 'showTextDocument') {\n\t\tawait vscode.window.showTextDocument(doc);\n\t\treturn;\n\t}\n\tif (action.kind === 'setSelections') {\n\t\teditor.selections = action.selections.map(s => new vscode.Selection(\n\t\t\tnew vscode.Position(s.start[0], s.start[1]),\n\t\t\tnew vscode.Position(s.end[0], s.end[1])\n\t\t));\n\t\teditor.revealRange(editor.selections[0], vscode.TextEditorRevealType.InCenterIfOutsideViewport);\n\t\treturn;\n\t}\n\tif (action.kind === 'editInsert') {\n\t\tawait editor.edit((e: vscode.TextEditorEdit) => e.insert(new vscode.Position(action.position[0], action.position[1]), action.text));\n\t\treturn;\n\t}\n\tif (action.kind === 'editDelete') {\n\t\tconst range = new vscode.Range(\n\t\t\tnew vscode.Position(action.range.start[0], action.range.start[1]),\n\t\t\tnew vscode.Position(action.range.end[0], action.range.end[1])\n\t\t);\n\t\tawait editor.edit((e: vscode.TextEditorEdit) => e.delete(range));\n\t\treturn;\n\t}\n\tif (action.kind === 'editReplace') {\n\t\tconst range = new vscode.Range(\n\t\t\tnew vscode.Position(action.range.start[0], action.range.start[1]),\n\t\t\tnew vscode.Position(action.range.end[0], action.range.end[1])\n\t\t);\n\t\tawait editor.edit((e: vscode.TextEditorEdit) => e.replace(range, action.text));\n\t\treturn;\n\t}\n\tif (action.kind === 'terminalShow') {\n\t\tconst term = getActiveOrCreateTerminal();\n\t\tterm.show();\n\t\treturn;\n\t}\n\tif (action.kind === 'terminalSendText') {\n\t\tconst term = getActiveOrCreateTerminal();\n\t\tterm.show();\n\t\tterm.sendText(action.text, false);\n\t\treturn;\n\t}\n\tif (action.kind === 'openFile') {\n\t\tconst uri = vscode.Uri.file(action.filePath);\n\t\tconst openedEditor = await vscode.window.showTextDocument(uri);\n\t\tif (action.selections) {\n\t\t\topenedEditor.selections = action.selections.map(s => new vscode.Selection(\n\t\t\t\tnew vscode.Position(s.start[0], s.start[1]),\n\t\t\t\tnew vscode.Position(s.end[0], s.end[1])\n\t\t\t));\n\t\t\topenedEditor.revealRange(openedEditor.selections[0], vscode.TextEditorRevealType.InCenterIfOutsideViewport);\n\t\t}\n\t\treturn;\n\t}\n}\n\n// -------------------- UI State & Helpers --------------------\nconst UI_CONTEXT_KEY = 'crowdPilot.uiVisible';\nlet previewVisible = false;\nlet decorationDeleteType: vscode.TextEditorDecorationType | undefined;\nlet decorationReplaceType: vscode.TextEditorDecorationType | undefined;\nlet decorationReplaceBlockType: vscode.TextEditorDecorationType | undefined;\nlet mockStep = 0;\nlet suppressAutoPreview = false;\nlet latestRequestId = 0;\nlet currentAbortController: AbortController | undefined;\n\nconst PREDICTION_DEBOUNCE_MS = 150;\nconst PREDICTION_THROTTLE_MS = 300;\n\ntype PendingPrediction = { id: number; timer: NodeJS.Timeout };\n\nlet nextQueuedPredictionId = 0;\nlet pendingPredictions: PendingPrediction[] = [];\nconst cancelledPredictionIds = new Set<number>();\nlet lastPredictionTimestamp: number | undefined;\n\nfunction disposePreviewDecorations() {\n\ttry { decorationDeleteType?.dispose(); } catch {}\n\ttry { decorationReplaceType?.dispose(); } catch {}\n\ttry { decorationReplaceBlockType?.dispose(); } catch {}\n\tdecorationDeleteType = undefined;\n\tdecorationReplaceType = undefined;\n\tdecorationReplaceBlockType = undefined;\n}\n\nfunction getDynamicMargin(editor: vscode.TextEditor, anchorLine: number, text: string): string {\n\tconst lines = text.split(/\r?\n/);\n\tconst height = lines.length;\n\t\n\t// We need to check the document lines that will be covered by this panel.\n\t// The panel starts at 'anchorLine' and extends downwards by 'height' lines.\n\t// However, visually, since it's 'after', it sits to the right of 'anchorLine',\n\t// and then flows down.\n\t// So we check document lines from anchorLine to anchorLine + height - 1.\n\t\n\tconst doc = editor.document;\n\tlet maxLen = 0;\n\tconst startLine = anchorLine;\n\tconst endLine = Math.min(doc.lineCount - 1, anchorLine + height - 1);\n\t\n\tfor (let i = startLine; i <= endLine; i++) {\n\t\tconst lineText = doc.lineAt(i).text;\n\t\tconst len = lineText.replace(/\t/g, ' ').length;\n\t\tif (len > maxLen) {\n\t\t\tmaxLen = len;\n\t\t}\n\t}\n\t\n\tconst anchorLineText = doc.lineAt(anchorLine).text;\n\tconst anchorLen = anchorLineText.replace(/\t/g, ' ').length;\n\t\n\tconst diff = Math.max(0, maxLen - anchorLen);\n\tconst margin = diff + 4; \n\treturn `${margin}ch`;\n}\n\nfunction showPreviewUI(action: Action): void {\n\tconst editor = vscode.window.activeTextEditor;\n\tif (!editor) { return; }\n\tdisposePreviewDecorations();\n\n\tconst next = (action.kind === 'editInsert' || action.kind === 'editDelete' || action.kind === 'editReplace' || action.kind === 'terminalSendText' || action.kind === 'setSelections' || action.kind === 'openFile') ? action : undefined;\n\tif (!next) {\n\t\tpreviewVisible = false;\n\t\tvscode.commands.executeCommand('setContext', UI_CONTEXT_KEY, false);\n\t\tcurrentAction = action;\n\t\treturn;\n\t}\n\n\tconst trimText = (t: string) => {\n\t\tconst oneLine = t.replace(/\r?\n/g, '\\n');\n\t\treturn oneLine.length > 80 ? oneLine.slice(0, 77) + '…' : oneLine;\n\t};\n\n\tif (next.kind === 'setSelections') {\n\t\tconst selection = next.selections[0];\n\t\tconst targetPos = new vscode.Position(selection.start[0], selection.start[1]);\n\t\tconst isVisible = editor.visibleRanges.some(r => r.contains(targetPos));\n\t\t\n\t\tlet anchorPos = targetPos;\n\t\tlet label = ""↳ Move Cursor Here"";\n\n\t\tif (!isVisible && editor.visibleRanges.length > 0) {\n\t\t\tconst firstVisible = editor.visibleRanges[0].start;\n\t\t\tconst lastVisible = editor.visibleRanges[editor.visibleRanges.length - 1].end;\n\t\t\t\n\t\t\tif (targetPos.isBefore(firstVisible)) {\n\t\t\t\tanchorPos = new vscode.Position(firstVisible.line, Number.MAX_VALUE);\n\t\t\t} else {\n\t\t\t\tanchorPos = new vscode.Position(lastVisible.line, Number.MAX_VALUE);\n\t\t\t}\n\n\t\t\tif (targetPos.line < anchorPos.line) {\n\t\t\t\tlabel = `↑ Move Cursor to Line ${targetPos.line + 1}`;\n\t\t\t} else {\n\t\t\t\tlabel = `↓ Move Cursor to Line ${targetPos.line + 1}`;\n\t\t\t}\n\t\t}\n\n\t\tconst margin = getDynamicMargin(editor, anchorPos.line, label);\n\n\t\tdecorationReplaceBlockType = vscode.window.createTextEditorDecorationType({\n\t\t\tafter: {\n\t\t\t\tcontentText: '',\n\t\t\t\tcolor: new vscode.ThemeColor('charts.purple'),\n\t\t\t\tbackgroundColor: new vscode.ThemeColor('editor.background'),\n\t\t\t\tfontStyle: 'italic',\n\t\t\t\tfontWeight: '600',\n\t\t\t\tmargin: `0 0 0 ${margin}`,\n\t\t\t\ttextDecoration: `none; display: inline-block; white-space: pre; content: ""${label}""; border: 1px solid var(--vscode-charts-purple); padding: 4px; border-radius: 4px; box-shadow: 0 4px 8px rgba(0,0,0,0.25); pointer-events: none; position: relative; z-index: 100; vertical-align: top;`\n\t\t\t}\n\t\t});\n\t\teditor.setDecorations(decorationReplaceBlockType, [{ range: new vscode.Range(anchorPos, anchorPos) }]);\n\t} else if (next.kind === 'terminalSendText') {\n\t\tconst cursor = editor.selection.active;\n\t\tconst isVisible = editor.visibleRanges.some(r => r.contains(cursor));\n\t\t\n\t\tlet anchorPos = new vscode.Position(cursor.line, Number.MAX_VALUE);\n\t\t\n\t\tif (!isVisible && editor.visibleRanges.length > 0) {\n\t\t\tconst firstVisible = editor.visibleRanges[0].start;\n\t\t\tconst lastVisible = editor.visibleRanges[editor.visibleRanges.length - 1].end;\n\t\t\t\n\t\t\tif (cursor.isBefore(firstVisible)) {\n\t\t\t\tanchorPos = new vscode.Position(firstVisible.line, Number.MAX_VALUE);\n\t\t\t} else {\n\t\t\t\tanchorPos = new vscode.Position(lastVisible.line, Number.MAX_VALUE);\n\t\t\t}\n\t\t}\n\t\t\n\t\tconst summary = trimText(next.text || '');\n\t\tconst label = `↳ Execute shell command in terminal: ${summary}`;\n\t\tconst margin = getDynamicMargin(editor, anchorPos.line, label);\n\n\t\tdecorationReplaceBlockType = vscode.window.createTextEditorDecorationType({\n\t\t\tafter: {\n\t\t\t\tcontentText: '',\n\t\t\t\tcolor: new vscode.ThemeColor('charts.purple'),\n\t\t\t\tbackgroundColor: new vscode.ThemeColor('editor.background'),\n\t\t\t\tfontStyle: 'italic',\n\t\t\t\tfontWeight: '600',\n\t\t\t\tmargin: `0 0 0 ${margin}`,\n\t\t\t\ttextDecoration: `none; display: inline-block; white-space: pre; content: ""${label.replace(/""/g, '\\""')}""; border: 1px solid var(--vscode-charts-purple); padding: 4px; border-radius: 4px; box-shadow: 0 4px 8px rgba(0,0,0,0.25); pointer-events: none; position: relative; z-index: 100; vertical-align: top;`\n\t\t\t}\n\t\t});\n\t\teditor.setDecorations(decorationReplaceBlockType, [{ range: new vscode.Range(anchorPos, anchorPos) }]);\n\t} else if (next.kind === 'editInsert') {\n\t\tconst posLine = next.position[0];\n\t\tconst fullBlock = next.text;\n\t\tconst cssContent = fullBlock\n\t\t\t.replace(/""/g, '\\""')\n\t\t\t.replace(/\r?\n/g, '\\A ');\n\n\t\tconst docLineCount = editor.document.lineCount;\n\t\tlet anchorLine = posLine;\n\t\tlet shiftUp = true;\n\t\t\n\t\tif (anchorLine >= docLineCount) {\n\t\t\tanchorLine = docLineCount - 1;\n\t\t\tshiftUp = false;\n\t\t}\n\n\t\tconst anchorPos = new vscode.Position(anchorLine, Number.MAX_VALUE); \n\t\t\n\t\tconst marginCheckLine = anchorLine;\n\t\tconst margin = getDynamicMargin(editor, marginCheckLine, fullBlock);\n\n\t\tconst topOffset = '0';\n\n\t\tconst beforeDecoration = {\n\t\t\tcontentText: '',\n\t\t\ttextDecoration: `none; position: absolute; left: 0; width: 100vw; border-top: 1px dashed var(--vscode-charts-purple); top: 0; height: 0; z-index: 99; pointer-events: none;`\n\t\t};\n\n\t\tdecorationReplaceBlockType = vscode.window.createTextEditorDecorationType({\n\t\t\tbefore: beforeDecoration,\n\t\t\tafter: {\n\t\t\t\tcontentText: '',\n\t\t\t\tcolor: new vscode.ThemeColor('charts.purple'),\n\t\t\t\tbackgroundColor: new vscode.ThemeColor('editor.background'),\n\t\t\t\tfontStyle: 'italic',\n\t\t\t\tfontWeight: '600',\n\t\t\t\tmargin: `0 0 0 ${margin}`,\n\t\t\t\ttextDecoration: `none; display: inline-block; white-space: pre; content: ""${cssContent}""; border: 1px solid var(--vscode-charts-purple); padding: 4px; border-radius: 4px; box-shadow: 0 4px 8px rgba(0,0,0,0.25); pointer-events: none; position: relative; z-index: 100; vertical-align: top; top: ${topOffset};`\n\t\t\t}\n\t\t});\n\t\teditor.setDecorations(decorationReplaceBlockType, [{ range: new vscode.Range(anchorPos, anchorPos) }]);\n\t} else if (next.kind === 'editDelete') {\n\t\tconst range = new vscode.Range(\n\t\t\tnew vscode.Position(next.range.start[0], next.range.start[1]),\n\t\t\tnew vscode.Position(next.range.end[0], next.range.end[1])\n\t\t);\n\t\tdecorationDeleteType = vscode.window.createTextEditorDecorationType({\n\t\t\tbackgroundColor: 'rgba(255, 60, 60, 0.18)',\n\t\t\tborder: '1px solid rgba(255, 60, 60, 0.35)',\n\t\t\ttextDecoration: 'line-through'\n\t\t});\n\t\teditor.setDecorations(decorationDeleteType, [{ range }]);\n\t} else if (next.kind === 'editReplace') {\n\t\tconst range = new vscode.Range(\n\t\t\tnew vscode.Position(next.range.start[0], next.range.start[1]),\n\t\t\tnew vscode.Position(next.range.end[0], next.range.end[1])\n\t\t);\n\t\tdecorationReplaceType = vscode.window.createTextEditorDecorationType({\n\t\t\tbackgroundColor: 'rgba(255,165,0,0.15)',\n\t\t\tborder: '1px dashed rgba(255,165,0,0.45)',\n\t\t\tcolor: new vscode.ThemeColor('disabledForeground'),\n\t\t\ttextDecoration: 'line-through'\n\t\t});\n\t\teditor.setDecorations(decorationReplaceType, [{ range }]);\n\n\t\tconst fullBlock = next.text;\n\t\t\n\t\tconst cssContent = fullBlock\n\t\t\t.replace(/""/g, '\\""')\n\t\t\t.replace(/\r?\n/g, '\\A '); \n\n\t\tconst anchorLine = range.start.line;\n\t\tconst anchorPos = new vscode.Position(anchorLine, Number.MAX_VALUE);\n\t\tconst margin = getDynamicMargin(editor, anchorLine, fullBlock);\n\n\t\tdecorationReplaceBlockType = vscode.window.createTextEditorDecorationType({\n\t\t\tafter: {\n\t\t\t\tcontentText: '',\n\t\t\t\tcolor: new vscode.ThemeColor('charts.purple'),\n\t\t\t\tbackgroundColor: new vscode.ThemeColor('editor.background'),\n\t\t\t\tfontStyle: 'italic',\n\t\t\t\tfontWeight: '600',\n\t\t\t\tmargin: `0 0 0 ${margin}`,\n\t\t\t\ttextDecoration: `none; display: inline-block; white-space: pre; content: ""${cssContent}""; border: 1px solid var(--vscode-charts-purple); padding: 4px; border-radius: 4px; box-shadow: 0 4px 8px rgba(0,0,0,0.25); pointer-events: none; position: relative; z-index: 100; vertical-align: top;`\n\t\t\t}\n\t\t});\n\t\teditor.setDecorations(decorationReplaceBlockType, [{ range: new vscode.Range(anchorPos, anchorPos) }]);\n\t} else if (next.kind === 'openFile') {\n\t\tconst cursor = editor.selection.active;\n\t\tconst isVisible = editor.visibleRanges.some(r => r.contains(cursor));\n\t\t\n\t\tlet anchorPos = new vscode.Position(cursor.line, Number.MAX_VALUE);\n\t\t\n\t\tif (!isVisible && editor.visibleRanges.length > 0) {\n\t\t\tconst firstVisible = editor.visibleRanges[0].start;\n\t\t\tconst lastVisible = editor.visibleRanges[editor.visibleRanges.length - 1].end;\n\t\t\t\n\t\t\tif (cursor.isBefore(firstVisible)) {\n\t\t\t\tanchorPos = new vscode.Position(firstVisible.line, Number.MAX_VALUE);\n\t\t\t} else {\n\t\t\t\tanchorPos = new vscode.Position(lastVisible.line, Number.MAX_VALUE);\n\t\t\t}\n\t\t}\n\t\t\n\t\tconst fileName = next.filePath.split(/[/\\]/).pop() || next.filePath;\n\t\tconst targetLine = next.selections?.[0]?.start[0];\n\t\tconst label = targetLine !== undefined\n\t\t\t? `↳ Switch to file: ${fileName}:${targetLine + 1}` // Display as 1-based\n\t\t\t: `↳ Switch to file: ${fileName}`;\n\t\tconst margin = getDynamicMargin(editor, anchorPos.line, label);\n\n\t\tdecorationReplaceBlockType = vscode.window.createTextEditorDecorationType({\n\t\t\tafter: {\n\t\t\t\tcontentText: '',\n\t\t\t\tcolor: new vscode.ThemeColor('charts.purple'),\n\t\t\t\tbackgroundColor: new vscode.ThemeColor('editor.background'),\n\t\t\t\tfontStyle: 'italic',\n\t\t\t\tfontWeight: '600',\n\t\t\t\tmargin: `0 0 0 ${margin}`,\n\t\t\t\ttextDecoration: `none; display: inline-block; white-space: pre; content: ""${label.replace(/""/g, '\\""')}""; border: 1px solid var(--vscode-charts-purple); padding: 4px; border-radius: 4px; box-shadow: 0 4px 8px rgba(0,0,0,0.25); pointer-events: none; position: relative; z-index: 100; vertical-align: top;`\n\t\t\t}\n\t\t});\n\t\teditor.setDecorations(decorationReplaceBlockType, [{ range: new vscode.Range(anchorPos, anchorPos) }]);\n\t}\n\n\tpreviewVisible = true;\n\tvscode.commands.executeCommand('setContext', UI_CONTEXT_KEY, true);\n\tcurrentAction = action;\n}\n\nfunction hidePreviewUI(suppress?: boolean): void {\n\tdisposePreviewDecorations();\n\tpreviewVisible = false;\n\tvscode.commands.executeCommand('setContext', UI_CONTEXT_KEY, false);\n\tif (suppress) {\n\t\tsuppressAutoPreview = true;\n\t}\n}\n\n/**\n * Schedule a model preview refresh, coalescing rapid editor events and\n * throttling how often we actually talk to the model.\n */\nfunction schedulePredictionRefresh(debounce: boolean, userRequested: boolean): void {\n\tif (!suggestionsEnabled) {\n\t\treturn;\n\t}\n\tif (!userRequested && suppressAutoPreview) {\n\t\treturn;\n\t}\n\n\tconst editor = vscode.window.activeTextEditor;\n\tif (!editor) {\n\t\thidePreviewUI();\n\t\treturn;\n\t}\n\n\tif (!userRequested) {\n\t\tif (!vscode.window.state.focused) {\n\t\t\thidePreviewUI();\n\t\t\treturn;\n\t\t}\n\t\tif (editor.document.getText().length === 0) {\n\t\t\thidePreviewUI();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tconst now = Date.now();\n\tconst id = ++nextQueuedPredictionId;\n\n\tlet delay = 0;\n\tif (debounce) {\n\t\tdelay = Math.max(delay, PREDICTION_DEBOUNCE_MS);\n\t}\n\tif (lastPredictionTimestamp !== null && lastPredictionTimestamp !== undefined) {\n\t\tconst elapsed = now - lastPredictionTimestamp;\n\t\tif (elapsed < PREDICTION_THROTTLE_MS) {\n\t\t\tdelay = Math.max(delay, PREDICTION_THROTTLE_MS - elapsed);\n\t\t}\n\t}\n\n\tconst timer = setTimeout(() => {\n\t\tif (cancelledPredictionIds.has(id)) {\n\t\t\tcancelledPredictionIds.delete(id);\n\t\t\treturn;\n\t\t}\n\n\t\tlastPredictionTimestamp = Date.now();\n\t\tpendingPredictions = pendingPredictions.filter(p => p.id !== id);\n\n\t\tvoid autoShowNextAction();\n\t}, delay);\n\n\tpendingPredictions.push({ id, timer });\n\n\tif (pendingPredictions.length > 2) {\n\t\tconst oldest = pendingPredictions.shift();\n\t\tif (oldest) {\n\t\t\tcancelledPredictionIds.add(oldest.id);\n\t\t\tclearTimeout(oldest.timer);\n\t\t}\n\t}\n}\n\nasync function autoShowNextAction(): Promise<void> {\n\tif (suppressAutoPreview) { return; }\n\tconst editor = vscode.window.activeTextEditor;\n\tif (!editor) { return; }\n\ttry {\n\t\tcurrentAbortController?.abort();\n\t\tconst controller = new AbortController();\n\t\tcurrentAbortController = controller;\n\t\tconst requestId = ++latestRequestId;\n\t\tconst next = await requestModelActions(editor, controller.signal);\n\t\tif (requestId !== latestRequestId) { return; }\n\t\tif (next) { showPreviewUI(next); } else { hidePreviewUI(); }\n\t} catch (err) {\n\t\tconst e = err as any;\n\t\tconst isAbort = e?.name === 'AbortError' || /aborted/i.test(String(e?.message ?? ''));\n\t\tif (isAbort) { return; }\n\t\thidePreviewUI();\n\t}\n}\n\n// -------------------- SGLang Client (simple test) --------------------\nasync function callSGLangChat(): Promise<void> {\n\tconst cfg = getConfig();\n\tconst headers: any = {\n\t\t'Content-Type': 'application/json'\n\t};\n\n\n\tconst requestBody: any = {\n\t\tmodel: cfg.modelName,\n\t\tmessages: [\n\t\t\t{ role: 'user', content: 'What is the capital of France?' }\n\t\t]\n\t};\n\trequestBody.temperature = 0.7;\n\trequestBody.top_p = 0.8;\n\trequestBody.top_k = 20;\n\trequestBody.min_p = 0;\n\trequestBody.chat_template_kwargs = {\n\t\tenable_thinking: false\n\t};\n\tconst postData = JSON.stringify(requestBody);\n\theaders['Content-Length'] = Buffer.byteLength(postData);\n\n\tconst options = {\n\t\thostname: cfg.hostname,\n\t\tport: cfg.port,\n\t\tpath: cfg.basePath,\n\t\tmethod: 'POST',\n\t\theaders\n\t};\n\n\n\ttry {\n\t\tconst json = await new Promise<any>((resolve, reject) => {\n\t\t\tconst req = http.request(options, (res: http.IncomingMessage) => {\n\t\t\t\tlet data = '';\n\t\t\t\tres.on('data', (chunk: Buffer) => {\n\t\t\t\t\tdata += chunk.toString();\n\t\t\t\t});\n\t\t\t\tres.on('end', () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresolve(JSON.parse(data));\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\treject(new Error(`Failed to parse response: ${err instanceof Error ? err.message : String(err)}`));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\n\t\t\treq.on('error', (err: Error) => {\n\t\t\t\treject(err);\n\t\t\t});\n\n\t\t\treq.write(postData);\n\t\t\treq.end();\n\t\t});\n\n\t\tvscode.window.showInformationMessage(`Response: ${JSON.stringify(json, null, 2)}`);\n\t} catch (err) {\n\t\tconst errorMessage = err instanceof Error ? err.message : String(err);\n\t\tvscode.window.showErrorMessage(`Request failed: ${errorMessage}`);\n\t}\n}\n\n// -------------------- Model-planned Actions --------------------\nasync function requestModelActions(editor: vscode.TextEditor, signal?: AbortSignal): Promise<Action> {\n\tconst cfg = getConfig();\n\tconst headers: any = {\n\t\t'Content-Type': 'application/json'\n\t};\n\n\tconst doc = editor.document;\n\n\t// FIXME (f.srambical): This should be the system prompt that was used during serialization.\n\tconst systemPrompt = [\n\t\t'You are a helpful assistant that interacts with a computer shell to solve programming tasks.',\n\t\t'Your goal is to predict the next bash command a developer would most likely execute, given their editing and navigation history.',\n\t\t'',\n\t\t'=== CONVERSATION FORMAT ===',\n\t\t'The conversation history alternates between:',\n\t\t'- Assistant messages: bash commands in fenced code blocks',\n\t\t'- User messages: command output wrapped in <stdout>...</stdout> tags',\n\t\t'',\n\t\t'File contents are displayed with 6-character right-aligned line numbers followed by a tab, e.g.:',\n\t\t' 1\tfirst line',\n\t\t' 2\tsecond line',\n\t\t'',\n\t\t'File content is typically shown in viewports of ~20 lines around the area of interest.',\n\t\t'',\n\t\t'=== RESPONSE FORMAT ===',\n\t\t'Your response must contain exactly ONE bash code block with one command or two commands connected with &&.',\n\t\t'',\n\t\t'<format_example>',\n\t\t'```bash',\n\t\t'your_command_here',\n\t\t'```',\n\t\t'</format_example>',\n\t\t'',\n\t\t'Failure to follow these rules will cause your response to be rejected.',\n\t\t'',\n\t\t'=== EDIT COMMAND FORMAT (IMPORTANT) ===',\n\t\t'When you want to EDIT a file, you MUST encode the edit using line-based sed commands in ONE of the following forms,',\n\t\t'and you MUST NOT use substitution commands like ""Ns/old/new/g"".',\n\t\t'',\n\t\t'Assume all line numbers are 1-based and paths are absolute.',\n\t\t'Allowed edit encodings (choose exactly one per response):',\n\t\t'',\n\t\t'1) Replace a contiguous block of lines:',\n\t\t"" sed -i 'START,ENDc\\"",\n\t\t'NEW_LINE_1',\n\t\t'NEW_LINE_2',\n\t\t""..."",\n\t\t""' /abs/path/to/file && cat -n /abs/path/to/file | sed -n 'VSTART,VENDp'"",\n\t\t'',\n\t\t'2) Delete a contiguous block of lines:',\n\t\t"" sed -i 'START,ENDd' /abs/path/to/file && cat -n /abs/path/to/file | sed -n 'VSTART,VENDp'"",\n\t\t'',\n\t\t'3) Insert new lines BEFORE a given line:',\n\t\t"" sed -i 'STARTi\\"",\n\t\t'NEW_LINE_1',\n\t\t'NEW_LINE_2',\n\t\t""..."",\n\t\t""' /abs/path/to/file && cat -n /abs/path/to/file | sed -n 'VSTART,VENDp'"",\n\t\t'',\n\t\t'4) Append new lines at the END of the file:',\n\t\t"" sed -i '$a\\"",\n\t\t'NEW_LINE_1',\n\t\t'NEW_LINE_2',\n\t\t""..."",\n\t\t""' /abs/path/to/file && cat -n /abs/path/to/file | sed -n 'VSTART,VENDp'"",\n\t\t'',\n\t\t'Where VSTART and VEND specify a small viewport around the edited region.',\n\t\t'',\n\t\t'Do NOT emit commands like ""3s/print/print()/g"" or any other ""s/old/new/"" style sed substitution; instead,',\n\t\t'always rewrite the affected lines using one of the line-based forms above.',\n\t\t'',\n\t\t'When you are NOT editing files (e.g., running tests, git commands, tools, etc.), you may emit arbitrary bash commands.'\n\t].join('\n');\n\n\tconst accumulatedMessages = conversationManager.finalizeForModel();\n\t\n\tlet conversationMessages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }> = [\n\t\t{ role: 'system', content: systemPrompt },\n\t];\n\t\n\tfor (const msg of accumulatedMessages) {\n\t\tconst role = msg.from === 'User' ? 'user' : 'assistant';\n\t\tconversationMessages.push({ role, content: msg.value });\n\t}\n\n\tconversationMessages = truncateToContextLimit(conversationMessages, cfg.maxContextTokens);\n\n\tconst requestBody: any = {\n\t\tmodel: cfg.modelName,\n\t\tmessages: conversationMessages\n\t};\n\trequestBody.temperature = 0.7;\n\trequestBody.top_p = 0.8;\n\trequestBody.top_k = 20;\n\trequestBody.min_p = 0;\n\trequestBody.logprobs = true;\n\trequestBody.chat_template_kwargs = {\n\t\tenable_thinking: false\n\t};\n\n\tconst postData = JSON.stringify(requestBody);\n\theaders['Content-Length'] = Buffer.byteLength(postData);\n\n\tconst options: any = {\n\t\thostname: cfg.hostname,\n\t\tport: cfg.port,\n\t\tpath: cfg.basePath,\n\t\tmethod: 'POST',\n\t\theaders\n\t};\n\tif (signal) {\n\t\toptions.signal = signal;\n\t}\n\n\tconst json = await new Promise<any>((resolve, reject) => {\n\t\tconst req = http.request(options, (res: http.IncomingMessage) => {\n\t\t\tlet data = '';\n\t\t\tres.on('data', (chunk: Buffer) => { data += chunk.toString(); });\n\t\t\tres.on('end', () => {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(JSON.parse(data));\n\t\t\t\t} catch (err) {\n\t\t\t\t\treject(new Error(`Failed to parse response: ${err instanceof Error ? err.message : String(err)}`));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\treq.on('error', (err: Error) => reject(err));\n\t\treq.write(postData);\n\t\treq.end();\n\t});\n\n\tconst avgLogprob = calculateAverageLogprob(json);\n\tif (avgLogprob < cfg.minAvgLogprob) {\n\t\treturn undefined as any; // Low confidence, silently skip suggestion\n\t}\n\n\tconst content = extractChatContent(json);\n\tif (typeof content !== 'string' || content.trim().length === 0) {\n\t\tthrow new Error('Empty model content');\n\t}\n\tconst action = parseAction(content, doc);\n\tif (!action) {\n\t\tthrow new Error('No valid action parsed from model output');\n\t}\n\n\tmarkPendingAsIgnored();\n\n\tcreatePendingPreferenceSample(\n\t\tconversationMessages,\n\t\tcontent,\n\t\taction,\n\t\tavgLogprob,\n\t\tcfg.modelName\n\t);\n\n\treturn action;\n}\n\nfunction extractChatContent(json: any): string | undefined {\n\ttry {\n\t\tif (json && Array.isArray(json.choices) && json.choices[0]) {\n\t\t\tconst choice = json.choices[0];\n\t\t\tif (choice.message && typeof choice.message.content === 'string') {\n\t\t\t\treturn choice.message.content;\n\t\t\t}\n\t\t\tif (typeof choice.text === 'string') {\n\t\t\t\treturn choice.text;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Calculate average logprob per token from the API response.\n * Returns the mean of logprobs across all tokens (negative value, closer to 0 = more confident).\n * Returns -Infinity if logprobs are not available.\n */\nfunction calculateAverageLogprob(json: any): number {\n\tconst logprobs = json.choices[0]?.logprobs;\n\tconst sum = logprobs.content.reduce((s: number, t: any) => s + t.logprob, 0);\n\treturn sum / logprobs.content.length;\n}\n\nfunction parseAction(raw: string, doc?: vscode.TextDocument): Action | undefined {\n\tconst command = extractBashCommand(raw);\n\tif (!command) {\n\t\treturn undefined;\n\t}\n\tconst normalized = command.replace(/<think>[\s\S]*?<\/think>/gi, '').trim();\n\tif (!normalized) {\n\t\treturn undefined;\n\t}\n\tif (doc) {\n\t\tconst editAction = parseEditFromSedCommand(normalized, doc);\n\t\tif (editAction) {\n\t\t\treturn editAction;\n\t\t}\n\t\tconst viewportAction = parseViewportFromCatCommand(normalized, doc);\n\t\tif (viewportAction) {\n\t\t\treturn viewportAction;\n\t\t}\n\t}\n\treturn { kind: 'terminalSendText', text: normalized };\n}\n\n/**\n * Parse a sed-based edit command of the form emitted by the NeMo serializer into a VS Code edit action.\n *\n * Supported patterns (1-based line numbers, mirroring serialization_utils.py):\n * sed -i 'START,ENDc\n<replacement...>' <file> -> editReplace\n * sed -i 'START,ENDd' <file> -> editDelete\n * sed -i 'STARTi\n<insert...>' <file> -> editInsert (before START)\n * sed -i '$a\n<append...>' <file> -> editInsert (append at EOF)\n *\n * If the command does not match these patterns, returns undefined.\n */\nfunction parseEditFromSedCommand(command: string, doc: vscode.TextDocument): Action | undefined {\n\t// Only consider the first command before && / ||, since cat -n etc. are for viewport only.\n\tconst main = command.split(/&&|\|\|/)[0]?.trim() ?? '';\n\tif (!main) {\n\t\treturn undefined;\n\t}\n\n\t// Match: sed -i '<script>' <file>\n\tconst sedMatch = main.match(/sed\s+-i\s+'([\s\S]*?)'\s+([^\s&|]+)\s*$/);\n\tif (!sedMatch) {\n\t\treturn undefined;\n\t}\n\tconst script = sedMatch[1] ?? '';\n\tconst targetFile = sedMatch[2] ?? '';\n\tconst activePath = doc.uri.fsPath;\n\tif (targetFile !== activePath) {\n\t\treturn undefined;\n\t}\n\n\t// Delete: ""START,ENDd""\n\tconst deleteMatch = script.match(/^(\d+),(\d+)d$/);\n\tif (deleteMatch) {\n\t\tconst startLine1 = Number(deleteMatch[1]);\n\t\tconst endLine1 = Number(deleteMatch[2]);\n\t\tif (!Number.isFinite(startLine1) || !Number.isFinite(endLine1)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst startLine0 = Math.max(0, startLine1 - 1);\n\t\tconst endLine0 = Math.max(0, endLine1 - 1);\n\n\t\tlet endPosLine = endLine0 + 1;\n\t\tlet endPosChar = 0;\n\t\tif (endPosLine >= doc.lineCount) {\n\t\t\tendPosLine = doc.lineCount - 1;\n\t\t\tendPosChar = doc.lineAt(endPosLine).range.end.character;\n\t\t}\n\t\treturn {\n\t\t\tkind: 'editDelete',\n\t\t\trange: {\n\t\t\t\tstart: [startLine0, 0],\n\t\t\t\tend: [endPosLine, endPosChar],\n\t\t\t},\n\t\t};\n\t}\n\n\t// Replace: ""START,ENDc\newline<payload...>""\n\tconst replaceMatch = script.match(/^(\d+),(\d+)c\\\n([\s\S]*)$/);\n\tif (replaceMatch) {\n\t\tconst startLine1 = Number(replaceMatch[1]);\n\t\tconst endLine1 = Number(replaceMatch[2]);\n\t\tlet payload = replaceMatch[3] ?? '';\n\t\tif (!Number.isFinite(startLine1) || !Number.isFinite(endLine1)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tpayload = payload.replace(/'\""'\""'/g, ""'"");\n\t\t// Convert escape sequences to actual characters\n\t\tpayload = payload.replace(/\\n/g, '\n').replace(/\\t/g, '\t').replace(/\\'/g, ""'"").replace(/\\\\/g, '\\');\n\t\tconst startLine0 = Math.max(0, startLine1 - 1);\n\t\tconst endLine0 = Math.max(0, endLine1 - 1);\n\t\tconst startPos: [number, number] = [startLine0, 0];\n\n\t\tlet endPosLine = endLine0 + 1;\n\t\tlet endPosChar = 0;\n\t\tif (endPosLine >= doc.lineCount) {\n\t\t\tendPosLine = doc.lineCount - 1;\n\t\t\tendPosChar = doc.lineAt(endPosLine).range.end.character;\n\t\t}\n\n\t\tconst text = payload.endsWith('\n') ? payload : payload + '\n';\n\t\treturn {\n\t\t\tkind: 'editReplace',\n\t\t\trange: { start: startPos, end: [endPosLine, endPosChar] },\n\t\t\ttext,\n\t\t};\n\t}\n\n\tconst insertMatch = script.match(/^(\d+)i\\\n([\s\S]*)$/);\n\tif (insertMatch) {\n\t\tconst line1 = Number(insertMatch[1]);\n\t\tlet payload = insertMatch[2] ?? '';\n\t\tif (!Number.isFinite(line1)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tpayload = payload.replace(/'\""'\""'/g, ""'"");\n\t\t// Convert escape sequences to actual characters\n\t\tpayload = payload.replace(/\\n/g, '\n').replace(/\\t/g, '\t').replace(/\\'/g, ""'"").replace(/\\\\/g, '\\');\n\t\tconst insertLine0 = Math.max(0, line1 - 1);\n\t\tconst position: [number, number] = [insertLine0, 0];\n\t\tconst text = payload.endsWith('\n') ? payload : payload + '\n';\n\t\treturn {\n\t\t\tkind: 'editInsert',\n\t\t\tposition,\n\t\t\ttext,\n\t\t};\n\t}\n\n\tconst appendMatch = script.match(/^\$a\\\n([\s\S]*)$/);\n\tif (appendMatch) {\n\t\tlet payload = appendMatch[1] ?? '';\n\t\tpayload = payload.replace(/'\""'\""'/g, ""'"");\n\t\t// Convert escape sequences to actual characters\n\t\tpayload = payload.replace(/\\n/g, '\n').replace(/\\t/g, '\t').replace(/\\'/g, ""'"").replace(/\\\\/g, '\\');\n\t\tconst insertLine0 = doc.lineCount;\n\t\tconst position: [number, number] = [insertLine0, 0];\n\t\tconst needsLeadingNewline = doc.lineCount > 0;\n\t\tconst base = payload.endsWith('\n') ? payload : payload + '\n';\n\t\tconst text = needsLeadingNewline ? '\n' + base : base;\n\t\treturn {\n\t\t\tkind: 'editInsert',\n\t\t\tposition,\n\t\t\ttext,\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Parse viewport / selection commands of the form:\n * cat -n <file> | sed -n 'START,ENDp'\n *\n * into a lightweight VS Code selection move (setSelections). This mirrors how\n * selection and viewport events are serialized in serialization_utils.py.\n */\nfunction parseViewportFromCatCommand(command: string, doc: vscode.TextDocument): Action | undefined {\n\tconst main = command.split(/&&|\|\|/)[0]?.trim() ?? '';\n\tif (!main) {\n\t\treturn undefined;\n\t}\n\n\t// Simple file-open: cat -n <file>\n\tconst simpleCatMatch = main.match(/^cat\s+-n\s+([^\s|]+)\s*$/);\n\tif (simpleCatMatch) {\n\t\tconst targetFile = simpleCatMatch[1] ?? '';\n\t\tif (targetFile !== doc.uri.fsPath) {\n\t\t\treturn { kind: 'openFile', filePath: targetFile };\n\t\t}\n\t\t// Ensure the active document is visible; rely on existing editor to handle this.\n\t\treturn { kind: 'showTextDocument' };\n\t}\n\n\t// Viewport slice: cat -n <file> | sed -n 'START,ENDp'\n\tconst viewportMatch = main.match(/^cat\s+-n\s+([^\s|]+)\s*\|\s*sed\s+-n\s+'(\d+),(\d+)p'\s*$/);\n\tif (!viewportMatch) {\n\t\treturn undefined;\n\t}\n\n\tconst targetFile = viewportMatch[1] ?? '';\n\tconst startStr = viewportMatch[2] ?? '';\n\tconst endStr = viewportMatch[3] ?? '';\n\n\tconst startLine1 = Number(startStr);\n\tconst endLine1 = Number(endStr);\n\n\t// Place the cursor in the middle of the viewport (1-based to 0-based).\n\tconst center1 = Math.floor((startLine1 + endLine1) / 2);\n\tconst center0 = Math.max(0, center1 - 1);\n\n\tif (targetFile !== doc.uri.fsPath) {\n\t\treturn {\n\t\t\tkind: 'openFile',\n\t\t\tfilePath: targetFile,\n\t\t\tselections: [{ start: [center0, 0], end: [center0, 0] }]\n\t\t};\n\t}\n\tconst lastLine = Math.max(0, doc.lineCount - 1);\n\tconst line = Math.min(center0, lastLine);\n\n\treturn {\n\t\tkind: 'setSelections',\n\t\tselections: [\n\t\t\t{\n\t\t\t\tstart: [line, 0],\n\t\t\t\tend: [line, 0],\n\t\t\t},\n\t\t],\n\t};\n}\n\nfunction extractBashCommand(raw: string): string | undefined {\n\tif (!raw) {\n\t\treturn undefined;\n\t}\n\tconst trimmed = raw.trim();\n\tconst fenceMatch = trimmed.match(/```(?:bash)?\s*([\s\S]*?)```/i);\n\tif (fenceMatch && fenceMatch[1]) {\n\t\treturn fenceMatch[1];\n\t}\n\t// Fallback: treat entire response as the command\n\treturn trimmed.length > 0 ? trimmed : undefined;\n}",typescript,tab
|
| 3 |
+
2,237,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"2:41:49 PM [info] Activating crowd-code\n2:41:49 PM [info] Recording started\n2:41:49 PM [info] Initializing git provider using file system watchers...\n",Log,tab
|
| 4 |
+
3,273,"extension-output-pdoom-org.crowd-code-#1-crowd-code",150,0,"2:41:49 PM [info] Git repository found\n2:41:49 PM [info] Git provider initialized successfully\n2:41:49 PM [info] Initial git state: [object Object]\n",Log,content
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-752a7417-71d4-4957-9814-498a4313969f1763752672170-2025_11_21-20.18.00.979/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-75911912-40c4-4ec3-a711-47c0946a81a11767620334402-2026_01_05-14.39.02.36/source.csv
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Sequence,Time,File,RangeOffset,RangeLength,Text,Language,Type
|
| 2 |
+
2,668,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"2:39:02 PM [info] Activating crowd-code\n2:39:02 PM [info] Recording started\n2:39:02 PM [info] Initializing git provider using file system watchers...\n2:39:02 PM [info] Git repository found\n2:39:02 PM [info] Git provider initialized successfully\n2:39:02 PM [info] Initial git state: [object Object]\n",Log,tab
|
| 3 |
+
3,114272,"TERMINAL",0,0,"",,terminal_focus
|
| 4 |
+
4,119956,"TERMINAL",0,0,"module load nodejs",,terminal_command
|
| 5 |
+
5,119986,"TERMINAL",0,0,"]633;C",,terminal_output
|
| 6 |
+
6,120145,"TERMINAL",0,0,"]0;franz.srambical@hai-login2:~/crowd-pilot-extension",,terminal_output
|
| 7 |
+
7,122298,"TERMINAL",0,0,"npm run compile",,terminal_command
|
| 8 |
+
8,122349,"TERMINAL",0,0,"]633;C",,terminal_output
|
| 9 |
+
9,123599,"TERMINAL",0,0,"\r\n> crowd-pilot@0.0.1 compile\r\n> tsc -p ./\r\n\r\n",,terminal_output
|
| 10 |
+
10,125542,"TERMINAL",0,0,"[37;40mnpm[0m [0m[36;40mnotice[0m[35m[0m \r\n[0m[37;40mnpm[0m [0m[36;40mnotice[0m[35m[0m New [31mmajor[39m version of npm available! [31m10.5.2[39m -> [32m11.7.0[39m\r\n[0m[37;40mnpm[0m [0m[36;40mnotice[0m[35m[0m Changelog: [36mhttps://github.com/npm/cli/releases/tag/v11.7.0[39m\r\n[0m[37;40mnpm[0m [0m[36;40mnotice[0m[35m[0m Run [32mnpm install -g npm@11.7.0[39m to update!\r\n[0m[37;40mnpm[0m [0m[36;40mnotice[0m[35m[0m \r\n[0m]0;franz.srambical@hai-login2:~/crowd-pilot-extension",,terminal_output
|
| 11 |
+
11,128435,"TERMINAL",0,0,"ls",,terminal_command
|
| 12 |
+
12,128459,"TERMINAL",0,0,"]633;CCHANGELOG.md [0m[01;34mcrowd-pilot-serializer[0m LICENSE package.json [01;34msrc[0m\r\ncrowd-pilot-0.0.1.vsix [01;31mcrowd-pilot-serializer-0.1.0.tgz[0m [01;34mnode_modules[0m package-lock.json tsconfig.json\r\ncrowd-pilot-old.vsix eslint.config.mjs [01;34mout[0m README.md vsc-extension-quickstart.md\r\n]0;franz.srambical@hai-login2:~/crowd-pilot-extension",,terminal_output
|
| 13 |
+
13,1142697,"src/preview/index.ts",0,0,"import * as vscode from 'vscode';\nimport { Action, toVscodeRange, toVscodePosition, truncate } from './types';\nimport { DecorationPool, COLORS } from './decorations';\nimport { CrowdPilotInlineProvider } from './inlineProvider';\nimport { MetaActionHoverProvider } from './hoverProvider';\nimport { showPendingActionQuickPick, QuickPickResult } from './quickPick';\nimport { computeDeletionRanges } from '../utils/diff';\n\n// Re-export types\nexport { Action, toVscodeRange, toVscodePosition, truncate } from './types';\nexport { QuickPickResult } from './quickPick';\n\n/**\n * Manages the preview UI for suggested actions.\n * Single entry point for all preview rendering.\n */\nexport class PreviewManager {\n private decorationPool: DecorationPool;\n private inlineProvider: CrowdPilotInlineProvider;\n private hoverProvider: MetaActionHoverProvider;\n private hoverProviderDisposable: vscode.Disposable | null = null;\n private currentAction: Action | null = null;\n private visible: boolean = false;\n\n constructor() {\n this.decorationPool = new DecorationPool();\n this.inlineProvider = new CrowdPilotInlineProvider();\n this.hoverProvider = new MetaActionHoverProvider();\n }\n\n /**\n * Register all providers with VS Code.\n * Call this during extension activation.\n */\n register(context: vscode.ExtensionContext): void {\n // Register inline completion provider for all files\n context.subscriptions.push(\n vscode.languages.registerInlineCompletionItemProvider(\n { pattern: '**' },\n this.inlineProvider\n )\n );\n\n // Register hover provider for all files\n this.hoverProviderDisposable = vscode.languages.registerHoverProvider(\n { pattern: '**' },\n this.hoverProvider\n );\n context.subscriptions.push(this.hoverProviderDisposable);\n }\n\n /**\n * Show a preview for the given action.\n */\n show(action: Action): void {\n const editor = vscode.window.activeTextEditor;\n \n // Clear previous preview\n this.clear();\n \n this.currentAction = action;\n this.visible = true;\n\n // Route to appropriate renderer based on action type\n switch (action.kind) {\n case 'editInsert':\n this.showInsertPreview(action, editor);\n break;\n\n case 'editReplace':\n this.showReplacePreview(action, editor);\n break;\n\n case 'editDelete':\n this.showDeletePreview(action, editor);\n break;\n\n case 'terminalSendText':\n this.showTerminalCommandPreview(action, editor);\n break;\n\n case 'setSelections':\n this.showCursorMovePreview(action, editor);\n break;\n\n case 'openFile':\n this.showFileSwitchPreview(action, editor);\n break;\n\n case 'terminalShow':\n case 'showTextDocument':\n // These don't need previews\n break;\n }\n }\n\n /**\n * Clear all preview UI.\n */\n clear(): void {\n this.decorationPool.clearAll();\n this.inlineProvider.clearAction();\n this.hoverProvider.clearAction();\n this.currentAction = null;\n this.visible = false;\n }\n\n /**\n * Check if a preview is currently visible.\n */\n isVisible(): boolean {\n return this.visible;\n }\n\n /**\n * Get the current action being previewed.\n */\n getCurrentAction(): Action | null {\n return this.currentAction;\n }\n\n /**\n * Show the pending action in a quick pick (for terminal focus scenario).\n */\n async showQuickPick(): Promise<QuickPickResult> {\n if (!this.currentAction) {\n return null;\n }\n return showPendingActionQuickPick(this.currentAction);\n }\n\n /**\n * Dispose all resources.\n */\n dispose(): void {\n this.decorationPool.dispose();\n this.hoverProviderDisposable?.dispose();\n }\n\n // -------------------- Preview Renderers --------------------\n\n /**\n * Show preview for text insertion using inline completion.\n * Ghost text will appear at the insert position.\n * Shows a fallback indicator if the insert position is far from cursor.\n */\n private showInsertPreview(action: { kind: 'editInsert'; position: [number, number]; text: string }, editor?: vscode.TextEditor): void {\n // Use inline completion provider for ghost text\n this.inlineProvider.setAction(action);\n \n if (editor) {\n const anchorLine = Math.min(action.position[0], editor.document.lineCount - 1);\n const cursorLine = editor.selection.active.line;\n \n // If cursor is far from the insert position, VS Code may not show the ghost text\n // In that case, show a fallback indicator pointing to where the insert will happen\n if (!this.inlineProvider.isActionNearCursor(cursorLine)) {\n const lineNum = action.position[0] + 1; // 1-based for display\n this.showMetaIndicator(editor, cursorLine, '$(arrow-down)', `Insert at line ${lineNum}`, COLORS.cursorMove);\n }\n \n // Set up hover provider for detailed view\n this.hoverProvider.setAction(action, anchorLine);\n }\n }\n\n /**\n * Show preview for text replacement.\n * Always shows deletion decorations because VS Code's inline completion\n * only reliably shows ghost text when the range starts at/after the cursor.\n */\n private showReplacePreview(action: { kind: 'editReplace'; range: { start: [number, number]; end: [number, number] }; text: string }, editor?: vscode.TextEditor): void {\n // Try inline completion - it may or may not show depending on cursor position\n this.inlineProvider.setAction(action);\n\n if (editor) {\n const range = toVscodeRange(action.range);\n \n // Always show deletion decorations for replacements\n // VS Code's inline completion doesn't reliably show ghost text\n // when the replacement range doesn't start at the cursor position\n const deletionRanges = computeDeletionRanges(editor.document, range, action.text);\n \n if (deletionRanges.length > 0) {\n // Character-level deletion highlights\n const decorationOptions: vscode.DecorationOptions[] = deletionRanges.map(r => ({\n range: r\n }));\n this.decorationPool.setDecorations(editor, 'deletion-char', decorationOptions);\n } else {\n // Fall back to highlighting the entire range\n this.decorationPool.setDecorations(editor, 'deletion', [{ range }]);\n }\n \n // Also show what will replace it as a meta indicator at end of line\n const preview = truncate(action.text, 50);\n this.showMetaIndicator(editor, range.start.line, '$(replace)', `→ ${preview}`, COLORS.cursorMove);\n\n // Set hover provider for full details\n this.hoverProvider.setAction(action, range.start.line);\n }\n }\n\n /**\n * Show preview for text deletion with strikethrough decoration.\n */\n private showDeletePreview(action: { kind: 'editDelete'; range: { start: [number, number]; end: [number, number] } }, editor?: vscode.TextEditor): void {\n if (!editor) return;\n\n const range = toVscodeRange(action.range);\n \n // Highlight the deletion range\n this.decorationPool.setDecorations(editor, 'deletion', [{ range }]);\n\n // Set hover provider\n this.hoverProvider.setAction(action, range.start.line);\n }\n\n /**\n * Show preview for terminal command with indicator decoration.\n */\n private showTerminalCommandPreview(action: { kind: 'terminalSendText'; text: string }, editor?: vscode.TextEditor): void {\n if (!editor) return;\n\n const anchorLine = this.getVisibleAnchorLine(editor);\n const cmdPreview = truncate(action.text, 60);\n \n this.showMetaIndicator(editor, anchorLine, '$(terminal)', `Run: ${cmdPreview}`, COLORS.terminal);\n this.hoverProvider.setAction(action, anchorLine);\n }\n\n /**\n * Show preview for cursor movement with indicator decoration.\n */\n private showCursorMovePreview(action: { kind: 'setSelections'; selections: Array<{ start: [number, number]; end: [number, number] }> }, editor?: vscode.TextEditor): void {\n if (!editor) return;\n\n const targetLine = action.selections[0].start[0];\n const targetPos = new vscode.Position(targetLine, action.selections[0].start[1]);\n const isTargetVisible = editor.visibleRanges.some(r => r.contains(targetPos));\n\n let anchorLine: number;\n let icon: string;\n let label: string;\n\n if (isTargetVisible) {\n // Target is visible, show indicator at target\n anchorLine = targetLine;\n icon = '$(arrow-right)';\n label = 'Move cursor here';\n } else {\n // Target is off-screen, show indicator at edge of visible area\n anchorLine = this.getVisibleAnchorLine(editor);\n const direction = targetLine < anchorLine ? '↑' : '↓';\n icon = `$(arrow-${targetLine < anchorLine ? 'up' : 'down'})`;\n label = `Go to line ${targetLine + 1}`;\n }\n\n this.showMetaIndicator(editor, anchorLine, icon, label, COLORS.cursorMove);\n this.hoverProvider.setAction(action, anchorLine);\n }\n\n /**\n * Show preview for file switch with indicator decoration.\n */\n private showFileSwitchPreview(action: { kind: 'openFile'; filePath: string; selections?: Array<{ start: [number, number]; end: [number, number] }> }, editor?: vscode.TextEditor): void {\n if (!editor) return;\n\n const anchorLine = this.getVisibleAnchorLine(editor);\n const fileName = action.filePath.split(/[/\\]/).pop() || action.filePath;\n const targetLine = action.selections?.[0]?.start[0];\n \n const label = targetLine !== undefined\n ? `Open: ${fileName}:${targetLine + 1}`\n : `Open: ${fileName}`;\n\n this.showMetaIndicator(editor, anchorLine, '$(file)', label, COLORS.fileSwitch);\n this.hoverProvider.setAction(action, anchorLine);\n }\n\n // -------------------- Helper Methods --------------------\n\n /**\n * Show a meta-action indicator decoration at the specified line.\n */\n private showMetaIndicator(\n editor: vscode.TextEditor,\n line: number,\n icon: string,\n label: string,\n color: vscode.ThemeColor\n ): void {\n const anchorPos = new vscode.Position(line, Number.MAX_SAFE_INTEGER);\n const range = new vscode.Range(anchorPos, anchorPos);\n\n const decorationOptions: vscode.DecorationOptions[] = [{\n range,\n renderOptions: {\n after: {\n contentText: ` ${icon} ${label}`,\n color: color,\n fontStyle: 'italic',\n margin: '0 0 0 2ch',\n }\n }\n }];\n\n this.decorationPool.setDecorations(editor, 'meta-indicator', decorationOptions);\n }\n\n /**\n * Get a visible anchor line for decorations.\n * Returns the line of the cursor if visible, or a line at the edge of the visible area.\n */\n private getVisibleAnchorLine(editor: vscode.TextEditor): number {\n const cursor = editor.selection.active;\n const isVisible = editor.visibleRanges.some(r => r.contains(cursor));\n\n if (isVisible) {\n return cursor.line;\n }\n\n if (editor.visibleRanges.length > 0) {\n const firstVisible = editor.visibleRanges[0];\n const lastVisible = editor.visibleRanges[editor.visibleRanges.length - 1];\n\n if (cursor.isBefore(firstVisible.start)) {\n return firstVisible.start.line;\n } else {\n return lastVisible.end.line;\n }\n }\n\n return 0;\n }\n}\n\n",typescript,tab
|
| 14 |
+
14,1142698,"src/preview/index.ts",5471,0,"",typescript,selection_command
|
| 15 |
+
15,1530955,"src/preview/index.ts",0,12297,"",typescript,content
|
| 16 |
+
16,1531090,"src/preview/index.ts",0,0,"import * as vscode from 'vscode';\nimport { Action, toVscodeRange, toVscodePosition, truncate } from './types';\nimport { DecorationPool, COLORS } from './decorations';\nimport { CrowdPilotInlineProvider } from './inlineProvider';\nimport { MetaActionHoverProvider } from './hoverProvider';\nimport { showPendingActionQuickPick, QuickPickResult } from './quickPick';\nimport { computeDeletionRanges } from '../utils/diff';\n\n// Re-export types\nexport { Action, toVscodeRange, toVscodePosition, truncate } from './types';\nexport { QuickPickResult } from './quickPick';\n\n/**\n * Manages the preview UI for suggested actions.\n * Single entry point for all preview rendering.\n */\nexport class PreviewManager {\n private decorationPool: DecorationPool;\n private inlineProvider: CrowdPilotInlineProvider;\n private hoverProvider: MetaActionHoverProvider;\n private hoverProviderDisposable: vscode.Disposable | null = null;\n private currentAction: Action | null = null;\n private visible: boolean = false;\n\n constructor() {\n this.decorationPool = new DecorationPool();\n this.inlineProvider = new CrowdPilotInlineProvider();\n this.hoverProvider = new MetaActionHoverProvider();\n }\n\n /**\n * Register all providers with VS Code.\n * Call this during extension activation.\n */\n register(context: vscode.ExtensionContext): void {\n // Register inline completion provider for all files\n context.subscriptions.push(\n vscode.languages.registerInlineCompletionItemProvider(\n { pattern: '**' },\n this.inlineProvider\n )\n );\n\n // Register hover provider for all files\n this.hoverProviderDisposable = vscode.languages.registerHoverProvider(\n { pattern: '**' },\n this.hoverProvider\n );\n context.subscriptions.push(this.hoverProviderDisposable);\n }\n\n /**\n * Show a preview for the given action.\n */\n show(action: Action): void {\n const editor = vscode.window.activeTextEditor;\n \n // Clear previous preview\n this.clear();\n \n this.currentAction = action;\n this.visible = true;\n\n // Route to appropriate renderer based on action type\n switch (action.kind) {\n case 'editInsert':\n this.showInsertPreview(action, editor);\n break;\n\n case 'editReplace':\n this.showReplacePreview(action, editor);\n break;\n\n case 'editDelete':\n this.showDeletePreview(action, editor);\n break;\n\n case 'terminalSendText':\n this.showTerminalCommandPreview(action, editor);\n break;\n\n case 'setSelections':\n this.showCursorMovePreview(action, editor);\n break;\n\n case 'openFile':\n this.showFileSwitchPreview(action, editor);\n break;\n\n case 'terminalShow':\n case 'showTextDocument':\n // These don't need previews\n break;\n }\n }\n\n /**\n * Clear all preview UI.\n */\n clear(): void {\n this.decorationPool.clearAll();\n this.inlineProvider.clearAction();\n this.hoverProvider.clearAction();\n this.currentAction = null;\n this.visible = false;\n }\n\n /**\n * Check if a preview is currently visible.\n */\n isVisible(): boolean {\n return this.visible;\n }\n\n /**\n * Get the current action being previewed.\n */\n getCurrentAction(): Action | null {\n return this.currentAction;\n }\n\n /**\n * Show the pending action in a quick pick (for terminal focus scenario).\n */\n async showQuickPick(): Promise<QuickPickResult> {\n if (!this.currentAction) {\n return null;\n }\n return showPendingActionQuickPick(this.currentAction);\n }\n\n /**\n * Dispose all resources.\n */\n dispose(): void {\n this.decorationPool.dispose();\n this.hoverProviderDisposable?.dispose();\n }\n\n // -------------------- Preview Renderers --------------------\n\n /**\n * Check if an action can use inline completion (Case 1).\n * Case 1: Pure insertion at/after cursor position - use inline completion API.\n * Case 2: Anything else - use text decorators.\n */\n private canUseInlineCompletion(action: Action, editor: vscode.TextEditor): boolean {\n const cursor = editor.selection.active;\n \n if (action.kind === 'editInsert') {\n const insertPos = toVscodePosition(action.position);\n // Can use inline if inserting on same line at/after cursor, or on a later line\n if (insertPos.line > cursor.line) return true;\n if (insertPos.line === cursor.line && insertPos.character >= cursor.character) return true;\n return false;\n }\n \n if (action.kind === 'editReplace') {\n const range = toVscodeRange(action.range);\n // Can use inline only if the range starts at/after cursor (pure addition scenario)\n // AND the range is empty (no deletion)\n if (range.isEmpty && range.start.isAfterOrEqual(cursor)) return true;\n return false;\n }\n \n return false;\n }\n\n /**\n * Show preview for text insertion.\n * Case 1: Insert at/after cursor → inline completion (ghost text)\n * Case 2: Insert before cursor → decorations\n */\n private showInsertPreview(action: { kind: 'editInsert'; position: [number, number]; text: string }, editor?: vscode.TextEditor): void {\n if (!editor) return;\n \n const insertPos = toVscodePosition(action.position);\n const anchorLine = Math.min(action.position[0], editor.document.lineCount - 1);\n \n if (this.canUseInlineCompletion(action, editor)) {\n // Case 1: Use inline completion - clean ghost text\n this.inlineProvider.setAction(action);\n } else {\n // Case 2: Use decorations - show green insertion block\n this.showInsertionBlock(editor, anchorLine, action.text);\n }\n \n // Set up hover provider for detailed view\n this.hoverProvider.setAction(action, anchorLine);\n }\n\n /**\n * Show preview for text replacement.\n * Case 1: Empty range at/after cursor → inline completion (ghost text)\n * Case 2: Has deletions or before cursor → decorations (red deletion + green addition)\n */\n private showReplacePreview(action: { kind: 'editReplace'; range: { start: [number, number]; end: [number, number] }; text: string }, editor?: vscode.TextEditor): void {\n if (!editor) return;\n\n const range = toVscodeRange(action.range);\n \n if (this.canUseInlineCompletion(action, editor)) {\n // Case 1: Use inline completion only - no decorations\n this.inlineProvider.setAction(action);\n } else {\n // Case 2: Use decorations\n // Red strikethrough on text being deleted\n const deletionRanges = computeDeletionRanges(editor.document, range, action.text);\n \n if (deletionRanges.length > 0) {\n const decorationOptions: vscode.DecorationOptions[] = deletionRanges.map(r => ({\n range: r\n }));\n this.decorationPool.setDecorations(editor, 'deletion-char', decorationOptions);\n } else if (!range.isEmpty) {\n // Highlight entire range if no char-level diff but range is not empty\n this.decorationPool.setDecorations(editor, 'deletion', [{ range }]);\n }\n \n // Green highlight on text being added (show after the deletion line)\n this.showInsertionBlock(editor, range.end.line, action.text);\n }\n\n // Set hover provider for full details\n this.hoverProvider.setAction(action, range.start.line);\n }\n\n /**\n * Show the new/inserted text with green highlight as a block after the specified line.\n */\n private showInsertionBlock(editor: vscode.TextEditor, afterLine: number, text: string): void {\n const anchorLine = Math.min(afterLine, editor.document.lineCount - 1);\n const anchorPos = new vscode.Position(anchorLine, Number.MAX_SAFE_INTEGER);\n \n // Format text for display (escape for CSS content)\n const displayText = text.replace(/\n/g, '↵').replace(/\t/g, '→');\n const truncatedText = truncate(displayText, 80);\n \n const decorationOptions: vscode.DecorationOptions[] = [{\n range: new vscode.Range(anchorPos, anchorPos),\n renderOptions: {\n after: {\n contentText: ` + ${truncatedText}`,\n color: COLORS.insertion.foreground,\n backgroundColor: COLORS.insertion.background,\n fontStyle: 'normal',\n margin: '0 0 0 2ch',\n border: '1px solid',\n borderColor: COLORS.insertion.border,\n }\n }\n }];\n\n this.decorationPool.setDecorations(editor, 'insertion-block', decorationOptions);\n }\n\n /**\n * Show preview for text deletion with strikethrough decoration.\n */\n private showDeletePreview(action: { kind: 'editDelete'; range: { start: [number, number]; end: [number, number] } }, editor?: vscode.TextEditor): void {\n if (!editor) return;\n\n const range = toVscodeRange(action.range);\n \n // Highlight the deletion range\n this.decorationPool.setDecorations(editor, 'deletion', [{ range }]);\n\n // Set hover provider\n this.hoverProvider.setAction(action, range.start.line);\n }\n\n /**\n * Show preview for terminal command with indicator decoration.\n */\n private showTerminalCommandPreview(action: { kind: 'terminalSendText'; text: string }, editor?: vscode.TextEditor): void {\n if (!editor) return;\n\n const anchorLine = this.getVisibleAnchorLine(editor);\n const cmdPreview = truncate(action.text, 60);\n \n this.showMetaIndicator(editor, anchorLine, '$(terminal)', `Run: ${cmdPreview}`, COLORS.terminal);\n this.hoverProvider.setAction(action, anchorLine);\n }\n\n /**\n * Show preview for cursor movement with indicator decoration.\n */\n private showCursorMovePreview(action: { kind: 'setSelections'; selections: Array<{ start: [number, number]; end: [number, number] }> }, editor?: vscode.TextEditor): void {\n if (!editor) return;\n\n const targetLine = action.selections[0].start[0];\n const targetPos = new vscode.Position(targetLine, action.selections[0].start[1]);\n const isTargetVisible = editor.visibleRanges.some(r => r.contains(targetPos));\n\n let anchorLine: number;\n let icon: string;\n let label: string;\n\n if (isTargetVisible) {\n // Target is visible, show indicator at target\n anchorLine = targetLine;\n icon = '$(arrow-right)';\n label = 'Move cursor here';\n } else {\n // Target is off-screen, show indicator at edge of visible area\n anchorLine = this.getVisibleAnchorLine(editor);\n const direction = targetLine < anchorLine ? '↑' : '↓';\n icon = `$(arrow-${targetLine < anchorLine ? 'up' : 'down'})`;\n label = `Go to line ${targetLine + 1}`;\n }\n\n this.showMetaIndicator(editor, anchorLine, icon, label, COLORS.cursorMove);\n this.hoverProvider.setAction(action, anchorLine);\n }\n\n /**\n * Show preview for file switch with indicator decoration.\n */\n private showFileSwitchPreview(action: { kind: 'openFile'; filePath: string; selections?: Array<{ start: [number, number]; end: [number, number] }> }, editor?: vscode.TextEditor): void {\n if (!editor) return;\n\n const anchorLine = this.getVisibleAnchorLine(editor);\n const fileName = action.filePath.split(/[/\\]/).pop() || action.filePath;\n const targetLine = action.selections?.[0]?.start[0];\n \n const label = targetLine !== undefined\n ? `Open: ${fileName}:${targetLine + 1}`\n : `Open: ${fileName}`;\n\n this.showMetaIndicator(editor, anchorLine, '$(file)', label, COLORS.fileSwitch);\n this.hoverProvider.setAction(action, anchorLine);\n }\n\n // -------------------- Helper Methods --------------------\n\n /**\n * Show a meta-action indicator decoration at the specified line.\n */\n private showMetaIndicator(\n editor: vscode.TextEditor,\n line: number,\n icon: string,\n label: string,\n color: vscode.ThemeColor\n ): void {\n const anchorPos = new vscode.Position(line, Number.MAX_SAFE_INTEGER);\n const range = new vscode.Range(anchorPos, anchorPos);\n\n const decorationOptions: vscode.DecorationOptions[] = [{\n range,\n renderOptions: {\n after: {\n contentText: ` ${icon} ${label}`,\n color: color,\n fontStyle: 'italic',\n margin: '0 0 0 2ch',\n }\n }\n }];\n\n this.decorationPool.setDecorations(editor, 'meta-indicator', decorationOptions);\n }\n\n /**\n * Get a visible anchor line for decorations.\n * Returns the line of the cursor if visible, or a line at the edge of the visible area.\n */\n private getVisibleAnchorLine(editor: vscode.TextEditor): number {\n const cursor = editor.selection.active;\n const isVisible = editor.visibleRanges.some(r => r.contains(cursor));\n\n if (isVisible) {\n return cursor.line;\n }\n\n if (editor.visibleRanges.length > 0) {\n const firstVisible = editor.visibleRanges[0];\n const lastVisible = editor.visibleRanges[editor.visibleRanges.length - 1];\n\n if (cursor.isBefore(firstVisible.start)) {\n return firstVisible.start.line;\n } else {\n return lastVisible.end.line;\n }\n }\n\n return 0;\n }\n}\n\n\n",typescript,content
|
| 17 |
+
17,1531092,"src/preview/index.ts",14263,2,"",typescript,content
|
| 18 |
+
18,1531322,"src/utils/diff.ts",0,0,"import * as vscode from 'vscode';\n\n/**\n * Represents a segment of a diff result.\n */\ninterface DiffSegment {\n type: 'equal' | 'insert' | 'delete';\n value: string;\n}\n\n/**\n * Simple character-level diff implementation.\n * Uses a basic approach suitable for small text comparisons.\n * For larger texts, consider using the 'diff' npm package.\n */\nexport function diffChars(oldText: string, newText: string): DiffSegment[] {\n const segments: DiffSegment[] = [];\n \n // Use longest common subsequence approach for character diff\n const lcs = longestCommonSubsequence(oldText, newText);\n \n let oldIndex = 0;\n let newIndex = 0;\n let lcsIndex = 0;\n \n while (oldIndex < oldText.length || newIndex < newText.length) {\n // Handle deletions (chars in old but not in LCS)\n let deletedChars = '';\n while (oldIndex < oldText.length && \n (lcsIndex >= lcs.length || oldText[oldIndex] !== lcs[lcsIndex])) {\n deletedChars += oldText[oldIndex];\n oldIndex++;\n }\n if (deletedChars) {\n segments.push({ type: 'delete', value: deletedChars });\n }\n \n // Handle insertions (chars in new but not in LCS)\n let insertedChars = '';\n while (newIndex < newText.length && \n (lcsIndex >= lcs.length || newText[newIndex] !== lcs[lcsIndex])) {\n insertedChars += newText[newIndex];\n newIndex++;\n }\n if (insertedChars) {\n segments.push({ type: 'insert', value: insertedChars });\n }\n \n // Handle equal chars (from LCS)\n let equalChars = '';\n while (lcsIndex < lcs.length && \n oldIndex < oldText.length && \n newIndex < newText.length &&\n oldText[oldIndex] === lcs[lcsIndex] && \n newText[newIndex] === lcs[lcsIndex]) {\n equalChars += lcs[lcsIndex];\n oldIndex++;\n newIndex++;\n lcsIndex++;\n }\n if (equalChars) {\n segments.push({ type: 'equal', value: equalChars });\n }\n }\n \n return segments;\n}\n\n/**\n * Compute the longest common subsequence of two strings.\n */\nfunction longestCommonSubsequence(str1: string, str2: string): string {\n const m = str1.length;\n const n = str2.length;\n \n // Create DP table\n const dp: number[][] = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));\n \n // Fill DP table\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n if (str1[i - 1] === str2[j - 1]) {\n dp[i][j] = dp[i - 1][j - 1] + 1;\n } else {\n dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);\n }\n }\n }\n \n // Backtrack to find LCS\n let lcs = '';\n let i = m;\n let j = n;\n while (i > 0 && j > 0) {\n if (str1[i - 1] === str2[j - 1]) {\n lcs = str1[i - 1] + lcs;\n i--;\n j--;\n } else if (dp[i - 1][j] > dp[i][j - 1]) {\n i--;\n } else {\n j--;\n }\n }\n \n return lcs;\n}\n\n/**\n * Compute VS Code ranges for characters that will be deleted in a replacement.\n * These are characters in the old text that don't appear in the new text.\n */\nexport function computeDeletionRanges(\n doc: vscode.TextDocument,\n range: vscode.Range,\n newText: string\n): vscode.Range[] {\n const oldText = doc.getText(range);\n const diffs = diffChars(oldText, newText);\n \n const deletions: vscode.Range[] = [];\n let offset = doc.offsetAt(range.start);\n \n for (const segment of diffs) {\n if (segment.type === 'delete') {\n const startPos = doc.positionAt(offset);\n const endPos = doc.positionAt(offset + segment.value.length);\n deletions.push(new vscode.Range(startPos, endPos));\n }\n // Only advance offset for non-inserted parts (delete and equal)\n if (segment.type !== 'insert') {\n offset += segment.value.length;\n }\n }\n \n return deletions;\n}\n\n/**\n * Check if two texts have meaningful differences.\n * Returns false if texts are identical or only differ in whitespace.\n */\nexport function hasSignificantDiff(oldText: string, newText: string): boolean {\n if (oldText === newText) {\n return false;\n }\n // Normalize whitespace and compare\n const normalizedOld = oldText.replace(/\s+/g, ' ').trim();\n const normalizedNew = newText.replace(/\s+/g, ' ').trim();\n return normalizedOld !== normalizedNew;\n}\n\n\n",typescript,tab
|
| 19 |
+
19,1539906,"src/preview/index.ts",0,0,"",typescript,tab
|
| 20 |
+
20,1539908,"src/preview/index.ts",0,0,"",typescript,selection_command
|
| 21 |
+
21,1541553,"src/utils/diff.ts",0,0,"",typescript,tab
|
| 22 |
+
22,1543780,"src/preview/types.ts",0,0,"import * as vscode from 'vscode';\n\n/**\n * Action types that can be previewed and executed.\n */\nexport type Action =\n | { kind: 'showTextDocument' }\n | { kind: 'setSelections'; selections: Array<{ start: [number, number]; end: [number, number] }> }\n | { kind: 'editInsert'; position: [number, number]; text: string }\n | { kind: 'editDelete'; range: { start: [number, number]; end: [number, number] } }\n | { kind: 'editReplace'; range: { start: [number, number]; end: [number, number] }; text: string }\n | { kind: 'terminalShow' }\n | { kind: 'terminalSendText'; text: string }\n | { kind: 'openFile'; filePath: string; selections?: Array<{ start: [number, number]; end: [number, number] }> };\n\n/**\n * Convert action range to VS Code Range.\n */\nexport function toVscodeRange(range: { start: [number, number]; end: [number, number] }): vscode.Range {\n return new vscode.Range(\n new vscode.Position(range.start[0], range.start[1]),\n new vscode.Position(range.end[0], range.end[1])\n );\n}\n\n/**\n * Convert action position to VS Code Position.\n */\nexport function toVscodePosition(position: [number, number]): vscode.Position {\n return new vscode.Position(position[0], position[1]);\n}\n\n/**\n * Truncate text to a maximum length with ellipsis.\n */\nexport function truncate(text: string, maxLength: number): string {\n const oneLine = text.replace(/\r?\n/g, '↵');\n if (oneLine.length <= maxLength) {\n return oneLine;\n }\n return oneLine.slice(0, maxLength - 1) + '…';\n}\n\n\n",typescript,tab
|
| 23 |
+
23,1545715,"src/utils/diff.ts",0,0,"",typescript,tab
|
| 24 |
+
24,1595062,"src/preview/types.ts",0,0,"",typescript,tab
|
| 25 |
+
25,1619902,"src/utils/diff.ts",0,0,"",typescript,tab
|
| 26 |
+
26,1671757,"src/preview/hoverProvider.ts",0,0,"import * as vscode from 'vscode';\nimport { Action, truncate } from './types';\n\n/**\n * Provides hover tooltips for meta-action indicators.\n * Shows full content when hovering over truncated terminal commands, etc.\n */\nexport class MetaActionHoverProvider implements vscode.HoverProvider {\n private action: Action | null = null;\n private anchorLine: number | null = null;\n\n /**\n * Set the current action and its anchor line for hover detection.\n */\n setAction(action: Action, anchorLine: number): void {\n this.action = action;\n this.anchorLine = anchorLine;\n }\n\n /**\n * Clear the current action.\n */\n clearAction(): void {\n this.action = null;\n this.anchorLine = null;\n }\n\n /**\n * Provide hover content when user hovers over the indicator area.\n */\n provideHover(\n document: vscode.TextDocument,\n position: vscode.Position,\n token: vscode.CancellationToken\n ): vscode.ProviderResult<vscode.Hover> {\n if (!this.action || this.anchorLine === null) {\n return null;\n }\n\n // Check if hovering on the anchor line\n if (position.line !== this.anchorLine) {\n return null;\n }\n\n // Check if hovering past the line content (in the decoration area)\n const lineLength = document.lineAt(position.line).text.length;\n if (position.character < lineLength) {\n return null;\n }\n\n // Build hover content based on action type\n const content = this.buildHoverContent();\n if (!content) {\n return null;\n }\n\n return new vscode.Hover(content);\n }\n\n /**\n * Build markdown content for the hover based on action type.\n */\n private buildHoverContent(): vscode.MarkdownString | null {\n if (!this.action) {\n return null;\n }\n\n const md = new vscode.MarkdownString();\n md.isTrusted = true;\n\n switch (this.action.kind) {\n case 'terminalSendText':\n md.appendMarkdown('**Terminal Command**\n\n');\n md.appendCodeblock(this.action.text, 'bash');\n md.appendMarkdown('\n\n*Press Tab to execute, Esc to dismiss*');\n return md;\n\n case 'openFile':\n md.appendMarkdown('**Open File**\n\n');\n md.appendMarkdown(`\`${this.action.filePath}\``);\n if (this.action.selections?.[0]) {\n const line = this.action.selections[0].start[0] + 1;\n md.appendMarkdown(` at line ${line}`);\n }\n md.appendMarkdown('\n\n*Press Tab to open, Esc to dismiss*');\n return md;\n\n case 'setSelections':\n const targetLine = this.action.selections[0].start[0] + 1;\n md.appendMarkdown('**Move Cursor**\n\n');\n md.appendMarkdown(`Go to line ${targetLine}`);\n md.appendMarkdown('\n\n*Press Tab to move, Esc to dismiss*');\n return md;\n\n case 'editInsert':\n md.appendMarkdown('**Insert Text**\n\n');\n md.appendCodeblock(this.action.text, 'plaintext');\n md.appendMarkdown('\n\n*Press Tab to insert, Esc to dismiss*');\n return md;\n\n case 'editReplace':\n md.appendMarkdown('**Replace Text**\n\n');\n md.appendCodeblock(this.action.text, 'plaintext');\n md.appendMarkdown('\n\n*Press Tab to replace, Esc to dismiss*');\n return md;\n\n case 'editDelete':\n const startLine = this.action.range.start[0] + 1;\n const endLine = this.action.range.end[0] + 1;\n md.appendMarkdown('**Delete Text**\n\n');\n md.appendMarkdown(`Lines ${startLine}–${endLine}`);\n md.appendMarkdown('\n\n*Press Tab to delete, Esc to dismiss*');\n return md;\n\n default:\n return null;\n }\n }\n}\n\n\n",typescript,tab
|
| 27 |
+
27,1671934,"src/preview/quickPick.ts",0,0,"import * as vscode from 'vscode';\nimport { Action, truncate } from './types';\n\n/**\n * Result of the quick pick interaction.\n */\nexport type QuickPickResult = 'accept' | 'dismiss' | null;\n\n/**\n * Show a quick pick modal for the pending action.\n * Used when terminal is focused and decorations can't be shown.\n */\nexport async function showPendingActionQuickPick(action: Action): Promise<QuickPickResult> {\n const detail = formatActionDetail(action);\n \n const items: vscode.QuickPickItem[] = [\n { \n label: '$(check) Accept', \n description: 'Execute this action',\n detail: detail\n },\n { \n label: '$(x) Dismiss', \n description: 'Cancel this suggestion'\n },\n ];\n\n const result = await vscode.window.showQuickPick(items, {\n title: 'Pending Suggestion',\n placeHolder: getActionSummary(action),\n ignoreFocusOut: false,\n });\n\n if (result?.label.includes('Accept')) {\n return 'accept';\n }\n if (result?.label.includes('Dismiss')) {\n return 'dismiss';\n }\n return null;\n}\n\n/**\n * Get a short summary of the action for the quick pick placeholder.\n */\nfunction getActionSummary(action: Action): string {\n switch (action.kind) {\n case 'terminalSendText':\n return `Run terminal command`;\n case 'openFile':\n const fileName = action.filePath.split(/[/\\]/).pop() || action.filePath;\n return `Open file: ${fileName}`;\n case 'setSelections':\n return `Move cursor to line ${action.selections[0].start[0] + 1}`;\n case 'editInsert':\n return 'Insert text';\n case 'editReplace':\n return 'Replace text';\n case 'editDelete':\n return `Delete lines ${action.range.start[0] + 1}–${action.range.end[0] + 1}`;\n case 'terminalShow':\n return 'Show terminal';\n case 'showTextDocument':\n return 'Show document';\n default:\n return 'Execute action';\n }\n}\n\n/**\n * Format the full action detail for display in quick pick.\n */\nfunction formatActionDetail(action: Action): string {\n switch (action.kind) {\n case 'terminalSendText':\n return action.text;\n case 'openFile':\n if (action.selections?.[0]) {\n const line = action.selections[0].start[0] + 1;\n return `${action.filePath}:${line}`;\n }\n return action.filePath;\n case 'setSelections':\n const sel = action.selections[0];\n return `Line ${sel.start[0] + 1}, Column ${sel.start[1] + 1}`;\n case 'editInsert':\n return truncate(action.text, 200);\n case 'editReplace':\n return truncate(action.text, 200);\n case 'editDelete':\n return `Lines ${action.range.start[0] + 1} to ${action.range.end[0] + 1}`;\n default:\n return '';\n }\n}\n\n\n",typescript,tab
|
| 28 |
+
28,2296202,"TERMINAL",0,0,"watch",,terminal_focus
|
| 29 |
+
29,2297685,"TERMINAL",0,0,"bash",,terminal_focus
|
| 30 |
+
30,2783014,"TERMINAL",0,0,"watch",,terminal_focus
|
| 31 |
+
31,2783656,"TERMINAL",0,0,"bash",,terminal_focus
|
| 32 |
+
32,3758802,"src/preview/hoverProvider.ts",0,0,"",typescript,tab
|
| 33 |
+
33,3781804,"TERMINAL",0,0,"ls",,terminal_command
|
| 34 |
+
34,3781812,"TERMINAL",0,0,"]633;CCHANGELOG.md [0m[01;34mcrowd-pilot-serializer[0m LICENSE package.json [01;34msrc[0m\r\ncrowd-pilot-0.0.1.vsix [01;31mcrowd-pilot-serializer-0.1.0.tgz[0m [01;34mnode_modules[0m package-lock.json tsconfig.json\r\ncrowd-pilot-old.vsix eslint.config.mjs [01;34mout[0m README.md vsc-extension-quickstart.md\r\n]0;franz.srambical@hai-login2:~/crowd-pilot-extension",,terminal_output
|
| 35 |
+
35,3806846,"TERMINAL",0,0,"mv crowd-pilot-0.0.1.vsix crowd-pilot-old.vsix",,terminal_command
|
| 36 |
+
36,3806869,"TERMINAL",0,0,"]633;C]0;franz.srambical@hai-login2:~/crowd-pilot-extension",,terminal_output
|
| 37 |
+
37,3808917,"TERMINAL",0,0,"ls",,terminal_command
|
| 38 |
+
38,3808928,"TERMINAL",0,0,"]633;CCHANGELOG.md [0m[01;34mcrowd-pilot-serializer[0m eslint.config.mjs [01;34mnode_modules[0m package.json README.md tsconfig.json\r\ncrowd-pilot-old.vsix [01;31mcrowd-pilot-serializer-0.1.0.tgz[0m LICENSE [01;34mout[0m package-lock.json [01;34msrc[0m vsc-extension-quickstart.md\r\n]0;franz.srambical@hai-login2:~/crowd-pilot-extension",,terminal_output
|
| 39 |
+
39,3812274,"TERMINAL",0,0,"vsce package",,terminal_command
|
| 40 |
+
40,3812314,"TERMINAL",0,0,"]633;C",,terminal_output
|
| 41 |
+
41,3815876,"TERMINAL",0,0,"Executing prepublish script 'npm run vscode:prepublish'...\r\n",,terminal_output
|
| 42 |
+
42,3817126,"TERMINAL",0,0,"\r\n> crowd-pilot@0.0.1 vscode:prepublish\r\n> npm run compile\r\n\r\n",,terminal_output
|
| 43 |
+
43,3818288,"TERMINAL",0,0,"\r\n> crowd-pilot@0.0.1 compile\r\n> tsc -p ./\r\n\r\n",,terminal_output
|
| 44 |
+
44,3820190,"TERMINAL",0,0,"[37;40mnpm[0m [0m[36;40mnotice[0m[35m[0m \r\n[0m[37;40mnpm[0m [0m[36;40mnotice[0m[35m[0m New [31mmajor[39m version of npm available! [31m10.5.2[39m -> [32m11.7.0[39m\r\n[0m[37;40mnpm[0m [0m[36;40mnotice[0m[35m[0m Changelog: [36mhttps://github.com/npm/cli/releases/tag/v11.7.0[39m\r\n[0m[37;40mnpm[0m [0m[36;40mnotice[0m[35m[0m Run [32mnpm install -g npm@11.7.0[39m to update!\r\n[0m[37;40mnpm[0m [0m[36;40mnotice[0m[35m[0m \r\n[0m[37;40mnpm[0m [0m[36;40mnotice[0m[35m[0m \r\n[0m[37;40mnpm[0m [0m[36;40mnotice[0m[35m[0m New [31mmajor[39m version of npm available! [31m10.5.2[39m -> [32m11.7.0[39m\r\n[0m[37;40mnpm[0m [0m[36;40mnotice[0m[35m[0m Changelog: [36mhttps://github.com/npm/cli/releases/tag/v11.7.0[39m\r\n[0m[37;40mnpm[0m [0m[36;40mnotice[0m[35m[0m Run [32mnpm install -g npm@11.7.0[39m to update!\r\n[0m[37;40mnpm[0m [0m[36;40mnotice[0m[35m[0m \r\n[0m",,terminal_output
|
| 45 |
+
45,3822423,"TERMINAL",0,0,"[104m[30m INFO [39m[49m [1m[34mFiles included in the VSIX:[39m[22m\r\n[1m[34m[39m[22m[1mcrowd-pilot-0.0.1.vsix[22m\r\n├─ [Content_Types].xml \r\n├─ extension.vsixmanifest \r\n└─ [1mextension/[22m\r\n ├─ .crowd-pilot-preferences-qwen3_8b.jsonl [33m[21.25 MB][39m\r\n ├─ LICENSE.txt [90m[0.55 KB][39m\r\n ├─ crowd-pilot-serializer-0.1.0.tgz [90m[1022.98 KB][39m\r\n ├─ package.json [90m[4.83 KB][39m\r\n ├─ readme.md \r\n ├─ [1mnode_modules/[22m\r\n │ └─ [1m@crowd-pilot/[22m\r\n │ └─ [1mserializer/[22m [32m(3 files)[39m [90m[3.06 MB][39m\r\n └─ [1mout/[22m\r\n ├─ extension.js [90m[36.6 KB][39m\r\n ├─ extension.js.map [90m[31.36 KB][39m\r\n ├─ [1mpreview/[22m\r\n │ ├─ decorations.js [90m[6.16 KB][39m\r\n │ ├─ decorations.js.map [90m[3.12 KB][39m\r\n │ ├─ hoverProvider.js [90m[5.18 KB][39m\r\n │ ├─ hoverProvider.js.map [90m[2.99 KB][39m\r\n │ ├─ index.js [90m[17.41 KB][39m\r\n │ ├─ index.js.map [90m[10.71 KB][39m\r\n │ ├─ inlineProvider.js [90m[4.11 KB][39m\r\n │ ├─ inlineProvider.js.map [90m[1.96 KB][39m\r\n │ ├─ quickPick.js [90m[4.21 KB][39m\r\n │ ├─ quickPick.js.map [90m[2.39 KB][39m\r\n │ ├─ types.js [90m[2.22 KB][39m\r\n │ └─ types.js.map [90m[0.89 KB][39m\r\n ├─ [1mtest/[22m\r\n │ ├─ extension.test.js [90m[1.94 KB][39m\r\n │ └─ extension.test.js.map [90m[0.6 KB][39m\r\n └─ [1mutils/[22m\r\n ├─ diff.js [90m[10.26 KB][39m\r\n └─ diff.js.map [90m[7.58 KB][39m\r\n\r\n",,terminal_output
|
| 46 |
+
46,3824186,"TERMINAL",0,0,"[42m[30m DONE [39m[49m Packaged: /fast/home/franz.srambical/crowd-pilot-extension/crowd-pilot-0.0.1.vsix [1m(28 files, 3.79 MB)[22m\r\n]0;franz.srambical@hai-login2:~/crowd-pilot-extension",,terminal_output
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-78105cc3-5fe0-4c79-a145-2a2fd28c2d411758789399345-2025_09_25-10.36.42.235/source.csv
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Sequence,Time,File,RangeOffset,RangeLength,Text,Language,Type
|
| 2 |
+
1,3,"keyboards/annepro2/keymaps/calmar_one/keymap.c",0,0,"#include QMK_KEYBOARD_H\n#if __has_include(""keymap.h"")\n# include ""keymap.h""\n#endif\n\n\n/* THIS FILE WAS GENERATED!\n *\n * This file was generated by qmk json2c. You may or may not want to\n * edit it directly.\n */\n\nconst uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {\n [0] = LAYOUT_60_ansi(KC_ESC, KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, KC_MINS, KC_EQL, KC_BSPC, KC_TAB, KC_Q, KC_W, KC_E, KC_R, KC_T, KC_Y, KC_U, KC_I, KC_O, KC_P, KC_LBRC, KC_RBRC, KC_BSLS, KC_RCTL, LGUI_T(KC_A), LALT_T(KC_S), LCTL_T(KC_D), LSFT_T(KC_F), KC_G, KC_H, RSFT_T(KC_J), RCTL_T(KC_K), RALT_T(KC_L), RGUI_T(KC_SCLN), KC_QUOT, KC_ENT, KC_LSFT, KC_Z, LT(1,KC_X), LT(2,KC_C), LT(3,KC_V), KC_B, KC_N, LT(4,KC_M), LT(5,KC_COMM), KC_DOT, KC_SLSH, KC_UP, KC_LCTL, KC_LALT, KC_LGUI, KC_SPC, KC_RALT, KC_LEFT, KC_DOWN, KC_RGHT),\n [1] = LAYOUT_60_ansi(KC_NO, KC_AP2_BT1, KC_AP2_BT2, KC_AP2_BT3, KC_AP2_BT4, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_BRID, KC_BRIU, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_MPRV, KC_VOLD, KC_VOLU, KC_MNXT, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_MUTE, KC_MPLY, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO),\n [2] = LAYOUT_60_ansi(KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_LEFT, KC_DOWN, KC_UP, KC_RGHT, KC_CAPS, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_INS, KC_PGDN, KC_PGUP, KC_HOME, KC_END, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO),\n [3] = LAYOUT_60_ansi(KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, MS_BTN1, MS_BTN2, MS_BTN3, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, MS_LEFT, MS_DOWN, MS_UP, MS_RGHT, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, MS_WHLL, MS_WHLD, MS_WHLU, MS_WHLR, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO),\n [4] = LAYOUT_60_ansi(KC_NO, KC_NO, KC_NO, KC_LPRN, KC_RPRN, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_LCBR, KC_AMPR, KC_ASTR, KC_NO, KC_RCBR, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_COLN, KC_DLR, KC_PERC, KC_CIRC, KC_EQL, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_TILD, KC_EXLM, KC_AT, KC_HASH, KC_PIPE, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO),\n [5] = LAYOUT_60_ansi(KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_LBRC, KC_7, KC_8, KC_9, KC_RBRC, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_SCLN, KC_4, KC_5, KC_6, KC_EQL, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_GRV, KC_1, KC_2, KC_3, KC_BSLS, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO)\n};\n\n\n\n#ifdef OTHER_KEYMAP_C\n# include OTHER_KEYMAP_C\n#endif // OTHER_KEYMAP_C\n",c,tab
|
| 3 |
+
2,59,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"10:36:42 AM [info] Activating crowd-code\n10:36:42 AM [info] Recording started\n10:36:42 AM [info] Initializing git provider using file system watchers...\n10:36:42 AM [info] Git repository found\n10:36:42 AM [info] Git provider initialized successfully\n10:36:42 AM [info] Initial git state: [object Object]\n",Log,tab
|
| 4 |
+
3,1238,"keyboards/annepro2/keymaps/calmar_one/keymap.c",0,0,"",c,tab
|
| 5 |
+
4,32089,"keyboards/annepro2/keymaps/calmar_one/keymap.c",213,0,"",c,selection_command
|
| 6 |
+
5,32195,"keyboards/annepro2/keymaps/calmar_one/keymap.c",276,0,"",c,selection_command
|
| 7 |
+
6,32470,"keyboards/annepro2/keymaps/calmar_one/keymap.c",213,0,"",c,selection_command
|
| 8 |
+
7,32536,"keyboards/annepro2/keymaps/calmar_one/keymap.c",212,0,"",c,selection_command
|
| 9 |
+
8,40863,"keyboards/annepro2/keymaps/calmar_one/keymap.c",213,0,"",c,selection_command
|
| 10 |
+
9,40906,"keyboards/annepro2/keymaps/calmar_one/keymap.c",276,0,"",c,selection_command
|
| 11 |
+
10,41163,"keyboards/annepro2/keymaps/calmar_one/keymap.c",829,0,"",c,selection_command
|
| 12 |
+
11,41192,"keyboards/annepro2/keymaps/calmar_one/keymap.c",1318,0,"",c,selection_command
|
| 13 |
+
12,41223,"keyboards/annepro2/keymaps/calmar_one/keymap.c",1787,0,"",c,selection_command
|
| 14 |
+
13,41257,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2260,0,"",c,selection_command
|
| 15 |
+
14,41783,"keyboards/annepro2/keymaps/calmar_one/keymap.c",1787,0,"",c,selection_command
|
| 16 |
+
15,41895,"keyboards/annepro2/keymaps/calmar_one/keymap.c",1318,0,"",c,selection_command
|
| 17 |
+
16,42117,"keyboards/annepro2/keymaps/calmar_one/keymap.c",829,0,"",c,selection_command
|
| 18 |
+
17,59143,"keyboards/annepro2/keymaps/calmar_one/keymap.c",829,488," [1] = LAYOUT_60_ansi(KC_NO, KC_AP2_BT1, KC_AP2_BT2, KC_AP2_BT3, KC_AP2_BT4, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_BRID, KC_BRIU, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_MPRV, KC_VOLD, KC_VOLU, KC_MNXT, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_MUTE, KC_MPLY, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO),",c,selection_command
|
| 19 |
+
18,61442,"keyboards/annepro2/keymaps/calmar_one/keymap.c",829,0,"",c,selection_command
|
| 20 |
+
19,61795,"keyboards/annepro2/keymaps/calmar_one/keymap.c",1318,0,"",c,selection_command
|
| 21 |
+
20,61858,"keyboards/annepro2/keymaps/calmar_one/keymap.c",1787,0,"",c,selection_command
|
| 22 |
+
21,62015,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2260,0,"",c,selection_command
|
| 23 |
+
22,64647,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2741,0,"",c,selection_command
|
| 24 |
+
23,65249,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2741,452," [5] = LAYOUT_60_ansi(KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_LBRC, KC_7, KC_8, KC_9, KC_RBRC, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_SCLN, KC_4, KC_5, KC_6, KC_EQL, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_GRV, KC_1, KC_2, KC_3, KC_BSLS, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO)",c,selection_command
|
| 25 |
+
24,205421,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2741,452," [5] = LAYOUT_60_ansi(KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_LBRC, KC_7, KC_8, KC_9, KC_RBRC, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_SCLN, KC_4, KC_5, KC_6, KC_EQL, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_GRV, KC_1, KC_2, KC_3, KC_BSLS, KC_NO, KC_NO, KC_0, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO)",c,content
|
| 26 |
+
25,390669,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2896,0,"",c,selection_mouse
|
| 27 |
+
26,394889,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2741,0,"",c,selection_command
|
| 28 |
+
27,397902,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2745,0,"",c,selection_command
|
| 29 |
+
28,398149,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2746,0,"",c,selection_command
|
| 30 |
+
29,398175,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2747,0,"",c,selection_command
|
| 31 |
+
30,398208,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2749,0,"",c,selection_command
|
| 32 |
+
31,398240,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2751,0,"",c,selection_command
|
| 33 |
+
32,398275,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2765,0,"",c,selection_command
|
| 34 |
+
33,398307,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2766,0,"",c,selection_command
|
| 35 |
+
34,398460,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2771,0,"",c,selection_command
|
| 36 |
+
35,398714,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2773,0,"",c,selection_command
|
| 37 |
+
36,398740,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2778,0,"",c,selection_command
|
| 38 |
+
37,398773,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2780,0,"",c,selection_command
|
| 39 |
+
38,398807,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2785,0,"",c,selection_command
|
| 40 |
+
39,398841,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2787,0,"",c,selection_command
|
| 41 |
+
40,398875,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2792,0,"",c,selection_command
|
| 42 |
+
41,398907,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2794,0,"",c,selection_command
|
| 43 |
+
42,398941,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2799,0,"",c,selection_command
|
| 44 |
+
43,398974,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2801,0,"",c,selection_command
|
| 45 |
+
44,399008,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2806,0,"",c,selection_command
|
| 46 |
+
45,399040,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2808,0,"",c,selection_command
|
| 47 |
+
46,399075,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2813,0,"",c,selection_command
|
| 48 |
+
47,399107,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2815,0,"",c,selection_command
|
| 49 |
+
48,399141,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2820,0,"",c,selection_command
|
| 50 |
+
49,399174,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2822,0,"",c,selection_command
|
| 51 |
+
50,399215,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2827,0,"",c,selection_command
|
| 52 |
+
51,399240,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2829,0,"",c,selection_command
|
| 53 |
+
52,399274,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2834,0,"",c,selection_command
|
| 54 |
+
53,399307,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2836,0,"",c,selection_command
|
| 55 |
+
54,399341,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2841,0,"",c,selection_command
|
| 56 |
+
55,399373,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2843,0,"",c,selection_command
|
| 57 |
+
56,399407,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2848,0,"",c,selection_command
|
| 58 |
+
57,399440,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2850,0,"",c,selection_command
|
| 59 |
+
58,399473,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2855,0,"",c,selection_command
|
| 60 |
+
59,399506,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2857,0,"",c,selection_command
|
| 61 |
+
60,399540,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2862,0,"",c,selection_command
|
| 62 |
+
61,399573,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2864,0,"",c,selection_command
|
| 63 |
+
62,399607,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2869,0,"",c,selection_command
|
| 64 |
+
63,399640,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2871,0,"",c,selection_command
|
| 65 |
+
64,399674,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2878,0,"",c,selection_command
|
| 66 |
+
65,399706,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2880,0,"",c,selection_command
|
| 67 |
+
66,399741,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2884,0,"",c,selection_command
|
| 68 |
+
67,399773,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2886,0,"",c,selection_command
|
| 69 |
+
68,399807,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2890,0,"",c,selection_command
|
| 70 |
+
69,399840,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2892,0,"",c,selection_command
|
| 71 |
+
70,399874,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2896,0,"",c,selection_command
|
| 72 |
+
71,399906,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2898,0,"",c,selection_command
|
| 73 |
+
72,399941,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2905,0,"",c,selection_command
|
| 74 |
+
73,399973,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2907,0,"",c,selection_command
|
| 75 |
+
74,400007,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2912,0,"",c,selection_command
|
| 76 |
+
75,400040,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2914,0,"",c,selection_command
|
| 77 |
+
76,400074,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2919,0,"",c,selection_command
|
| 78 |
+
77,400107,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2921,0,"",c,selection_command
|
| 79 |
+
78,400140,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2926,0,"",c,selection_command
|
| 80 |
+
79,400173,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2928,0,"",c,selection_command
|
| 81 |
+
80,400207,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2933,0,"",c,selection_command
|
| 82 |
+
81,400240,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2935,0,"",c,selection_command
|
| 83 |
+
82,400274,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2940,0,"",c,selection_command
|
| 84 |
+
83,400307,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2942,0,"",c,selection_command
|
| 85 |
+
84,400340,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2947,0,"",c,selection_command
|
| 86 |
+
85,400373,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2949,0,"",c,selection_command
|
| 87 |
+
86,400407,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2954,0,"",c,selection_command
|
| 88 |
+
87,400440,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2956,0,"",c,selection_command
|
| 89 |
+
88,400474,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2961,0,"",c,selection_command
|
| 90 |
+
89,400506,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2963,0,"",c,selection_command
|
| 91 |
+
90,400541,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2968,0,"",c,selection_command
|
| 92 |
+
91,400573,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2970,0,"",c,selection_command
|
| 93 |
+
92,400607,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2977,0,"",c,selection_command
|
| 94 |
+
93,400640,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2979,0,"",c,selection_command
|
| 95 |
+
94,400675,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2983,0,"",c,selection_command
|
| 96 |
+
95,400708,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2985,0,"",c,selection_command
|
| 97 |
+
96,400740,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2989,0,"",c,selection_command
|
| 98 |
+
97,400773,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2991,0,"",c,selection_command
|
| 99 |
+
98,400807,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2995,0,"",c,selection_command
|
| 100 |
+
99,400840,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2997,0,"",c,selection_command
|
| 101 |
+
100,400874,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3003,0,"",c,selection_command
|
| 102 |
+
101,400906,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3005,0,"",c,selection_command
|
| 103 |
+
102,400941,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3010,0,"",c,selection_command
|
| 104 |
+
103,400973,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3012,0,"",c,selection_command
|
| 105 |
+
104,401007,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3017,0,"",c,selection_command
|
| 106 |
+
105,401039,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3019,0,"",c,selection_command
|
| 107 |
+
106,401074,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3024,0,"",c,selection_command
|
| 108 |
+
107,401107,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3026,0,"",c,selection_command
|
| 109 |
+
108,401140,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3031,0,"",c,selection_command
|
| 110 |
+
109,401181,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3033,0,"",c,selection_command
|
| 111 |
+
110,401207,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3038,0,"",c,selection_command
|
| 112 |
+
111,401240,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3040,0,"",c,selection_command
|
| 113 |
+
112,401273,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3045,0,"",c,selection_command
|
| 114 |
+
113,401306,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3047,0,"",c,selection_command
|
| 115 |
+
114,401340,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3052,0,"",c,selection_command
|
| 116 |
+
115,401373,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3054,0,"",c,selection_command
|
| 117 |
+
116,401407,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3059,0,"",c,selection_command
|
| 118 |
+
117,401440,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3061,0,"",c,selection_command
|
| 119 |
+
118,401474,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3067,0,"",c,selection_command
|
| 120 |
+
119,401506,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3069,0,"",c,selection_command
|
| 121 |
+
120,401540,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3073,0,"",c,selection_command
|
| 122 |
+
121,401573,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3075,0,"",c,selection_command
|
| 123 |
+
122,401607,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3079,0,"",c,selection_command
|
| 124 |
+
123,401640,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3081,0,"",c,selection_command
|
| 125 |
+
124,401674,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3085,0,"",c,selection_command
|
| 126 |
+
125,401706,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3087,0,"",c,selection_command
|
| 127 |
+
126,401740,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3094,0,"",c,selection_command
|
| 128 |
+
127,401773,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3096,0,"",c,selection_command
|
| 129 |
+
128,401807,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3101,0,"",c,selection_command
|
| 130 |
+
129,401839,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3103,0,"",c,selection_command
|
| 131 |
+
130,401874,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3108,0,"",c,selection_command
|
| 132 |
+
131,401906,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3110,0,"",c,selection_command
|
| 133 |
+
132,401941,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3114,0,"",c,selection_command
|
| 134 |
+
133,401973,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3116,0,"",c,selection_command
|
| 135 |
+
134,402007,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3121,0,"",c,selection_command
|
| 136 |
+
135,402039,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3123,0,"",c,selection_command
|
| 137 |
+
136,402074,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3128,0,"",c,selection_command
|
| 138 |
+
137,402107,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3130,0,"",c,selection_command
|
| 139 |
+
138,402140,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3135,0,"",c,selection_command
|
| 140 |
+
139,402173,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3137,0,"",c,selection_command
|
| 141 |
+
140,402207,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3142,0,"",c,selection_command
|
| 142 |
+
141,402240,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3144,0,"",c,selection_command
|
| 143 |
+
142,402274,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3149,0,"",c,selection_command
|
| 144 |
+
143,402307,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3151,0,"",c,selection_command
|
| 145 |
+
144,402350,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3156,0,"",c,selection_command
|
| 146 |
+
145,402373,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3158,0,"",c,selection_command
|
| 147 |
+
146,402407,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3163,0,"",c,selection_command
|
| 148 |
+
147,402440,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3165,0,"",c,selection_command
|
| 149 |
+
148,402473,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3170,0,"",c,selection_command
|
| 150 |
+
149,402506,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3172,0,"",c,selection_command
|
| 151 |
+
150,402540,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3177,0,"",c,selection_command
|
| 152 |
+
151,402573,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3179,0,"",c,selection_command
|
| 153 |
+
152,402606,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3184,0,"",c,selection_command
|
| 154 |
+
153,402639,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3186,0,"",c,selection_command
|
| 155 |
+
154,402674,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3191,0,"",c,selection_command
|
| 156 |
+
155,402707,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3193,0,"",c,selection_command
|
| 157 |
+
156,402740,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3196,0,"",c,selection_command
|
| 158 |
+
157,402774,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3197,0,"",c,selection_command
|
| 159 |
+
158,402807,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3198,0,"",c,selection_command
|
| 160 |
+
159,402840,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3199,0,"",c,selection_command
|
| 161 |
+
160,402873,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3200,0,"",c,selection_command
|
| 162 |
+
161,402907,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3206,0,"",c,selection_command
|
| 163 |
+
162,402940,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3221,0,"",c,selection_command
|
| 164 |
+
163,402973,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3226,0,"",c,selection_command
|
| 165 |
+
164,403007,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3234,0,"",c,selection_command
|
| 166 |
+
165,403040,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3249,0,"",c,selection_command
|
| 167 |
+
166,403073,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3250,0,"",c,selection_command
|
| 168 |
+
167,403107,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3256,0,"",c,selection_command
|
| 169 |
+
168,403141,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3259,0,"",c,selection_command
|
| 170 |
+
169,403173,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3274,0,"",c,selection_command
|
| 171 |
+
170,403899,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3249,0,"",c,selection_command
|
| 172 |
+
171,403971,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3221,0,"",c,selection_command
|
| 173 |
+
172,404125,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3199,0,"",c,selection_command
|
| 174 |
+
173,404260,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3198,0,"",c,selection_command
|
| 175 |
+
174,404411,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3197,0,"",c,selection_command
|
| 176 |
+
175,404530,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3196,0,"",c,selection_command
|
| 177 |
+
176,404903,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3193,0,"",c,selection_command
|
| 178 |
+
177,405114,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3191,0,"",c,selection_command
|
| 179 |
+
178,406557,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3194,0,"",c,selection_command
|
| 180 |
+
179,407096,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3191,0,"",c,selection_command
|
| 181 |
+
180,422046,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3194,0,"",c,selection_command
|
| 182 |
+
181,422220,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3191,0,"",c,selection_command
|
| 183 |
+
182,482050,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3186,0,"",c,selection_command
|
| 184 |
+
183,482302,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3184,0,"",c,selection_command
|
| 185 |
+
184,482322,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3179,0,"",c,selection_command
|
| 186 |
+
185,482356,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3177,0,"",c,selection_command
|
| 187 |
+
186,482389,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3172,0,"",c,selection_command
|
| 188 |
+
187,482423,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3170,0,"",c,selection_command
|
| 189 |
+
188,482456,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3165,0,"",c,selection_command
|
| 190 |
+
189,482489,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3163,0,"",c,selection_command
|
| 191 |
+
190,482523,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3158,0,"",c,selection_command
|
| 192 |
+
191,482558,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3156,0,"",c,selection_command
|
| 193 |
+
192,482683,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3151,0,"",c,selection_command
|
| 194 |
+
193,482933,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3149,0,"",c,selection_command
|
| 195 |
+
194,482967,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3144,0,"",c,selection_command
|
| 196 |
+
195,483000,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3142,0,"",c,selection_command
|
| 197 |
+
196,483033,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3137,0,"",c,selection_command
|
| 198 |
+
197,483180,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3135,0,"",c,selection_command
|
| 199 |
+
198,483433,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3130,0,"",c,selection_command
|
| 200 |
+
199,483462,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3128,0,"",c,selection_command
|
| 201 |
+
200,483491,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3123,0,"",c,selection_command
|
| 202 |
+
201,483644,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3121,0,"",c,selection_command
|
| 203 |
+
202,483824,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3116,0,"",c,selection_command
|
| 204 |
+
203,483967,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3114,0,"",c,selection_command
|
| 205 |
+
204,484121,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3110,0,"",c,selection_command
|
| 206 |
+
205,484288,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3108,0,"",c,selection_command
|
| 207 |
+
206,484667,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3110,0,"",c,selection_command
|
| 208 |
+
207,520290,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3108,0,"",c,selection_command
|
| 209 |
+
208,520463,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3103,0,"",c,selection_command
|
| 210 |
+
209,520621,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3101,0,"",c,selection_command
|
| 211 |
+
210,520772,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3096,0,"",c,selection_command
|
| 212 |
+
211,520942,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3094,0,"",c,selection_command
|
| 213 |
+
212,521081,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3087,0,"",c,selection_command
|
| 214 |
+
213,521540,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3085,0,"",c,selection_command
|
| 215 |
+
214,521720,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3081,0,"",c,selection_command
|
| 216 |
+
215,521896,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3079,0,"",c,selection_command
|
| 217 |
+
216,522100,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3075,0,"",c,selection_command
|
| 218 |
+
217,522268,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3073,0,"",c,selection_command
|
| 219 |
+
218,522432,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3069,0,"",c,selection_command
|
| 220 |
+
219,527834,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3073,0,"",c,selection_command
|
| 221 |
+
220,528098,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3075,0,"",c,selection_command
|
| 222 |
+
221,528259,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3079,0,"",c,selection_command
|
| 223 |
+
222,528429,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3081,0,"",c,selection_command
|
| 224 |
+
223,528596,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3085,0,"",c,selection_command
|
| 225 |
+
224,528792,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3087,0,"",c,selection_command
|
| 226 |
+
225,597322,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3094,0,"",c,selection_command
|
| 227 |
+
226,597507,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3096,0,"",c,selection_command
|
| 228 |
+
227,597716,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3101,0,"",c,selection_command
|
| 229 |
+
228,598435,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3096,0,"",c,selection_command
|
| 230 |
+
229,604710,"keyboards/annepro2/keymaps/calmar_one/keymap.c",2741,451," [5] = LAYOUT_60_ansi(KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_LBRC, KC_7, KC_8, KC_9, KC_RBRC, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_SCLN, KC_4, KC_5, KC_6, KC_EQL, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_GRV, KC_1, KC_2, KC_3, KC_BSLS, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO)",c,content
|
| 231 |
+
230,609799,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3090,0,"",c,selection_command
|
| 232 |
+
231,655845,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3094,0,"",c,selection_command
|
| 233 |
+
232,656047,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3096,0,"",c,selection_command
|
| 234 |
+
233,658956,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3101,0,"",c,selection_command
|
| 235 |
+
234,659128,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3103,0,"",c,selection_command
|
| 236 |
+
235,688838,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3103,5,"",c,content
|
| 237 |
+
236,689816,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3103,0,"K",c,content
|
| 238 |
+
237,689818,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3104,0,"",c,selection_keyboard
|
| 239 |
+
238,690248,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3104,0,"C",c,content
|
| 240 |
+
239,690250,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3105,0,"",c,selection_keyboard
|
| 241 |
+
240,690844,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3103,2,"KC_0",c,content
|
| 242 |
+
241,691292,"keyboards/annepro2/keymaps/calmar_one/keymap.c",3106,0,"",c,selection_command
|
| 243 |
+
242,697296,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"",Log,tab
|
| 244 |
+
243,699125,"keyboards/annepro2/keymaps/calmar_one/keymap.c",0,0,"",c,tab
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-7bef0c9e-0ef0-4ac6-8e84-5c42986c6b871756230969871-2025_08_26-19.57.46.431/source.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Sequence,Time,File,RangeOffset,RangeLength,Text,Language,Type
|
| 2 |
+
2,582,"extension-output-pdoom-org.crowd-code-#1-crowd-code",0,0,"7:57:46 PM [info] Activating crowd-code\n7:57:46 PM [info] Recording started\n7:57:46 PM [info] Initializing git provider using file system watchers...\n7:57:46 PM [info] No workspace folder found\n",Log,tab
|
| 3 |
+
3,2434,"extension-output-pdoom-org.crowd-code-#1-crowd-code",194,0,"7:57:48 PM [info] Retrying git provider initialization...\n7:57:48 PM [info] No workspace folder found\n",Log,content
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-807b3b7b-c934-4e4b-a90d-2ec4fc057e6d1764325879483-2025_11_28-11.31.34.63/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-823236e5-d9b8-4c96-ab4a-24b8972648001754120306348-2025_08_02-09.38.34.668/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-82b7e9d3-cb7d-497a-bae7-ac831bb4275e1757959063865-2025_09_15-19.57.49.653/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
1f15334ab7e6820c9fda17c961659882ef9853cc80f7356b9a9b22f286fd7389/crowd-code-83ba4202-5f73-4c54-861d-29dc5e6fd6df1758801545463-2025_09_25-13.59.28.362/source.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|