id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
155,673
import os import sys from pathlib import Path from typing import Tuple, Union import click from requests.exceptions import ConnectionError import lightning.app.core.constants as constants from lightning.app import __version__ as ver from lightning.app.cli import cmd_init, cmd_install, cmd_pl_init, cmd_react_ui_init from lightning.app.cli.commands.app_commands import _run_app_command from lightning.app.cli.commands.cd import cd from lightning.app.cli.commands.cp import cp from lightning.app.cli.commands.logs import logs from lightning.app.cli.commands.ls import ls from lightning.app.cli.commands.pwd import pwd from lightning.app.cli.commands.rm import rm from lightning.app.cli.connect.app import ( _list_app_commands, _retrieve_connection_to_an_app, connect_app, disconnect_app, ) from lightning.app.cli.connect.data import connect_data from lightning.app.cli.lightning_cli_delete import delete from lightning.app.cli.lightning_cli_launch import launch from lightning.app.cli.lightning_cli_list import get_list from lightning.app.core.constants import ENABLE_APP_COMMENT_COMMAND_EXECUTION, get_lightning_cloud_url from lightning.app.runners.cloud import CloudRuntime from lightning.app.runners.runtime import dispatch from lightning.app.runners.runtime_type import RuntimeType from lightning.app.utilities.app_commands import run_app_commands from lightning.app.utilities.app_helpers import Logger from lightning.app.utilities.cli_helpers import ( _check_environment_and_redirect, _check_version_and_upgrade, _format_input_env_variables, ) from lightning.app.utilities.exceptions import _ApiExceptionHandler from lightning.app.utilities.login import Auth from lightning.app.utilities.port import _find_lit_app_port def init_app(name: str) -> None: cmd_init.app(name)
null
155,674
import os import sys from pathlib import Path from typing import Tuple, Union import click from requests.exceptions import ConnectionError import lightning.app.core.constants as constants from lightning.app import __version__ as ver from lightning.app.cli import cmd_init, cmd_install, cmd_pl_init, cmd_react_ui_init from lightning.app.cli.commands.app_commands import _run_app_command from lightning.app.cli.commands.cd import cd from lightning.app.cli.commands.cp import cp from lightning.app.cli.commands.logs import logs from lightning.app.cli.commands.ls import ls from lightning.app.cli.commands.pwd import pwd from lightning.app.cli.commands.rm import rm from lightning.app.cli.connect.app import ( _list_app_commands, _retrieve_connection_to_an_app, connect_app, disconnect_app, ) from lightning.app.cli.connect.data import connect_data from lightning.app.cli.lightning_cli_delete import delete from lightning.app.cli.lightning_cli_launch import launch from lightning.app.cli.lightning_cli_list import get_list from lightning.app.core.constants import ENABLE_APP_COMMENT_COMMAND_EXECUTION, get_lightning_cloud_url from lightning.app.runners.cloud import CloudRuntime from lightning.app.runners.runtime import dispatch from lightning.app.runners.runtime_type import RuntimeType from lightning.app.utilities.app_commands import run_app_commands from lightning.app.utilities.app_helpers import Logger from lightning.app.utilities.cli_helpers import ( _check_environment_and_redirect, _check_version_and_upgrade, _format_input_env_variables, ) from lightning.app.utilities.exceptions import _ApiExceptionHandler from lightning.app.utilities.login import Auth from lightning.app.utilities.port import _find_lit_app_port The provided code snippet includes necessary dependencies for implementing the `init_pl_app` function. Write a Python function `def init_pl_app(source: Union[Tuple[str], Tuple[str, str]], name: str, overwrite: bool = False) -> None` to solve the following problem: Create an app from your PyTorch Lightning source files. Here is the function: def init_pl_app(source: Union[Tuple[str], Tuple[str, str]], name: str, overwrite: bool = False) -> None: """Create an app from your PyTorch Lightning source files.""" if len(source) == 1: script_path = source[0] source_dir = str(Path(script_path).resolve().parent) elif len(source) == 2: # enable type checking once https://github.com/python/mypy/issues/1178 is available source_dir, script_path = source else: click.echo( f"Incorrect number of arguments. You passed ({', '.join(source)}) but only either one argument" f" (script path) or two arguments (root dir, script path) are allowed. Examples:\n" f"lightning init pl-app ./path/to/script.py\n" f"lightning init pl-app ./code ./code/path/to/script.py", err=True, ) raise SystemExit(1) cmd_pl_init.pl_app(source_dir=source_dir, script_path=script_path, name=name, overwrite=overwrite)
Create an app from your PyTorch Lightning source files.
155,675
import os import sys from pathlib import Path from typing import Tuple, Union import click from requests.exceptions import ConnectionError import lightning.app.core.constants as constants from lightning.app import __version__ as ver from lightning.app.cli import cmd_init, cmd_install, cmd_pl_init, cmd_react_ui_init from lightning.app.cli.commands.app_commands import _run_app_command from lightning.app.cli.commands.cd import cd from lightning.app.cli.commands.cp import cp from lightning.app.cli.commands.logs import logs from lightning.app.cli.commands.ls import ls from lightning.app.cli.commands.pwd import pwd from lightning.app.cli.commands.rm import rm from lightning.app.cli.connect.app import ( _list_app_commands, _retrieve_connection_to_an_app, connect_app, disconnect_app, ) from lightning.app.cli.connect.data import connect_data from lightning.app.cli.lightning_cli_delete import delete from lightning.app.cli.lightning_cli_launch import launch from lightning.app.cli.lightning_cli_list import get_list from lightning.app.core.constants import ENABLE_APP_COMMENT_COMMAND_EXECUTION, get_lightning_cloud_url from lightning.app.runners.cloud import CloudRuntime from lightning.app.runners.runtime import dispatch from lightning.app.runners.runtime_type import RuntimeType from lightning.app.utilities.app_commands import run_app_commands from lightning.app.utilities.app_helpers import Logger from lightning.app.utilities.cli_helpers import ( _check_environment_and_redirect, _check_version_and_upgrade, _format_input_env_variables, ) from lightning.app.utilities.exceptions import _ApiExceptionHandler from lightning.app.utilities.login import Auth from lightning.app.utilities.port import _find_lit_app_port def init_component(name: str) -> None: cmd_init.component(name)
null
155,676
import os import sys from pathlib import Path from typing import Tuple, Union import click from requests.exceptions import ConnectionError import lightning.app.core.constants as constants from lightning.app import __version__ as ver from lightning.app.cli import cmd_init, cmd_install, cmd_pl_init, cmd_react_ui_init from lightning.app.cli.commands.app_commands import _run_app_command from lightning.app.cli.commands.cd import cd from lightning.app.cli.commands.cp import cp from lightning.app.cli.commands.logs import logs from lightning.app.cli.commands.ls import ls from lightning.app.cli.commands.pwd import pwd from lightning.app.cli.commands.rm import rm from lightning.app.cli.connect.app import ( _list_app_commands, _retrieve_connection_to_an_app, connect_app, disconnect_app, ) from lightning.app.cli.connect.data import connect_data from lightning.app.cli.lightning_cli_delete import delete from lightning.app.cli.lightning_cli_launch import launch from lightning.app.cli.lightning_cli_list import get_list from lightning.app.core.constants import ENABLE_APP_COMMENT_COMMAND_EXECUTION, get_lightning_cloud_url from lightning.app.runners.cloud import CloudRuntime from lightning.app.runners.runtime import dispatch from lightning.app.runners.runtime_type import RuntimeType from lightning.app.utilities.app_commands import run_app_commands from lightning.app.utilities.app_helpers import Logger from lightning.app.utilities.cli_helpers import ( _check_environment_and_redirect, _check_version_and_upgrade, _format_input_env_variables, ) from lightning.app.utilities.exceptions import _ApiExceptionHandler from lightning.app.utilities.login import Auth from lightning.app.utilities.port import _find_lit_app_port The provided code snippet includes necessary dependencies for implementing the `init_react_ui` function. Write a Python function `def init_react_ui(dest_dir: str) -> None` to solve the following problem: Create a react UI to give a Lightning component a React.js web user interface (UI) Here is the function: def init_react_ui(dest_dir: str) -> None: """Create a react UI to give a Lightning component a React.js web user interface (UI)""" cmd_react_ui_init.react_ui(dest_dir)
Create a react UI to give a Lightning component a React.js web user interface (UI)
155,677
import os import sys from pathlib import Path from typing import Tuple, Union import click from requests.exceptions import ConnectionError import lightning.app.core.constants as constants from lightning.app import __version__ as ver from lightning.app.cli import cmd_init, cmd_install, cmd_pl_init, cmd_react_ui_init from lightning.app.cli.commands.app_commands import _run_app_command from lightning.app.cli.commands.cd import cd from lightning.app.cli.commands.cp import cp from lightning.app.cli.commands.logs import logs from lightning.app.cli.commands.ls import ls from lightning.app.cli.commands.pwd import pwd from lightning.app.cli.commands.rm import rm from lightning.app.cli.connect.app import ( _list_app_commands, _retrieve_connection_to_an_app, connect_app, disconnect_app, ) from lightning.app.cli.connect.data import connect_data from lightning.app.cli.lightning_cli_delete import delete from lightning.app.cli.lightning_cli_launch import launch from lightning.app.cli.lightning_cli_list import get_list from lightning.app.core.constants import ENABLE_APP_COMMENT_COMMAND_EXECUTION, get_lightning_cloud_url from lightning.app.runners.cloud import CloudRuntime from lightning.app.runners.runtime import dispatch from lightning.app.runners.runtime_type import RuntimeType from lightning.app.utilities.app_commands import run_app_commands from lightning.app.utilities.app_helpers import Logger from lightning.app.utilities.cli_helpers import ( _check_environment_and_redirect, _check_version_and_upgrade, _format_input_env_variables, ) from lightning.app.utilities.exceptions import _ApiExceptionHandler from lightning.app.utilities.login import Auth from lightning.app.utilities.port import _find_lit_app_port import os ) ) "checkpoint_folder", ) "--output_file", ) """Set the environment variables for the new processes. The Fabric connector will parse the arguments set here. """ os.environ["LT_CLI_USED"] = "1" os.environ["LT_DEVICES"] = str(args.devices) os.environ["LT_NUM_NODES"] = str(args.num_nodes) def _prepare_file(file: str) -> str: exists = os.path.exists(file) if exists: return file raise FileNotFoundError(f"The provided file {file} hasn't been found.")
null
155,678
import os from typing import List from setuptools import find_packages, setup The provided code snippet includes necessary dependencies for implementing the `_load_requirements` function. Write a Python function `def _load_requirements(path_dir: str, file_name: str = "requirements.txt", comment_char: str = "#") -> List[str]` to solve the following problem: Load requirements from a file. Here is the function: def _load_requirements(path_dir: str, file_name: str = "requirements.txt", comment_char: str = "#") -> List[str]: """Load requirements from a file.""" with open(os.path.join(path_dir, file_name)) as file: lines = [ln.strip() for ln in file.readlines()] reqs = [] for ln in lines: # filer all comments if comment_char in ln: ln = ln[: ln.index(comment_char)].strip() # skip directly installed dependencies if ln.startswith("http"): continue # skip index url if ln.startswith("--extra-index-url"): continue if ln: # if requirement is not empty reqs.append(ln) return reqs
Load requirements from a file.
155,679
import json import os import shutil import sys from subprocess import Popen from typing import List, Optional, Tuple import click import psutil from lightning_utilities.core.imports import package_available from rich.progress import Progress from lightning.app.utilities.cli_helpers import _get_app_display_name, _LightningAppOpenAPIRetriever from lightning.app.utilities.cloud import _get_project from lightning.app.utilities.enum import OpenAPITags from lightning.app.utilities.log import get_logfile from lightning.app.utilities.network import LightningClient _PPID = os.getenv("LIGHTNING_CONNECT_PPID", str(psutil.Process(os.getpid()).ppid())) _LIGHTNING_CONNECTION_FOLDER = os.path.join(_LIGHTNING_CONNECTION, _PPID) def disconnect_app(logout: bool = False): """Disconnect from an App.""" _clean_lightning_connection() connected_file = os.path.join(_LIGHTNING_CONNECTION_FOLDER, "connect.txt") if os.path.exists(connected_file): with open(connected_file) as f: result = f.readlines()[0].replace("\n", "") os.remove(connected_file) commands_folder = os.path.join(_LIGHTNING_CONNECTION_FOLDER, "commands") if os.path.exists(commands_folder): shutil.rmtree(commands_folder) if result == "localhost": click.echo("You are disconnected from the local Lightning App.") else: click.echo(f"You are disconnected from the cloud Lightning App: {result}.") else: if not logout: click.echo( "You aren't connected to any Lightning App. " "Please use `lightning_app connect app_name_or_id` to connect to one." ) def _write_commands_metadata(api_commands): metadata = dict(api_commands.items()) metadata_path = os.path.join(_get_commands_folder(), ".meta.json") with open(metadata_path, "w") as f: json.dump(metadata, f) def _install_missing_requirements( retriever: _LightningAppOpenAPIRetriever, fail_if_missing: bool = False, ): requirements = set() for metadata in retriever.api_commands.values(): if metadata["tag"] == OpenAPITags.APP_CLIENT_COMMAND: for req in metadata.get("requirements", []) or []: requirements.add(req) if requirements: missing_requirements = [] for req in requirements: if not (package_available(req) or package_available(req.replace("-", "_"))): missing_requirements.append(req) if missing_requirements: if fail_if_missing: missing_requirements = " ".join(missing_requirements) print(f"The command failed as you are missing the following requirements: `{missing_requirements}`.") sys.exit(0) for req in missing_requirements: std_out_out = get_logfile("output.log") with open(std_out_out, "wb") as stdout: Popen( f"{sys.executable} -m pip install {req}", shell=True, stdout=stdout, stderr=stdout, ).wait() os.remove(std_out_out) def _clean_lightning_connection(): if not os.path.exists(_LIGHTNING_CONNECTION): return for ppid in os.listdir(_LIGHTNING_CONNECTION): try: psutil.Process(int(ppid)) except (psutil.NoSuchProcess, ValueError): connection = os.path.join(_LIGHTNING_CONNECTION, str(ppid)) if os.path.exists(connection): shutil.rmtree(connection) def _scan_lightning_connections(app_name_or_id): if not os.path.exists(_LIGHTNING_CONNECTION): return None for ppid in os.listdir(_LIGHTNING_CONNECTION): try: psutil.Process(int(ppid)) except (psutil.NoSuchProcess, ValueError): continue connection_path = os.path.join(_LIGHTNING_CONNECTION, str(ppid)) connected_file = os.path.join(connection_path, "connect.txt") curr_app_name, curr_app_id = _read_connected_file(connected_file) if not curr_app_name: continue if app_name_or_id in (curr_app_name, curr_app_id): return connection_path return None def _get_app_display_name(app: Externalv1LightningappInstance) -> str: return getattr(app, "display_name", None) or app.name class _LightningAppOpenAPIRetriever: def __init__( self, app_id_or_name_or_url: Optional[str], use_cache: bool = False, ): """This class encapsulates the logic to collect the openapi.json file from the app to use the CLI Commands. Arguments: app_id_or_name_or_url: An identified for the app. use_cache: Whether to load the openapi spec from the cache. """ self.app_id_or_name_or_url = app_id_or_name_or_url self.url = None self.openapi = None self.api_commands = None self.app_id = None self.app_name = None home = os.path.expanduser("~") if use_cache: cache_openapi = os.path.join(home, ".lightning", "lightning_connection", "commands", "openapi.json") if os.path.exists(cache_openapi): with open(cache_openapi) as f: self.openapi = json.load(f) self.api_commands = _extract_command_from_openapi(self.openapi) if not self.api_commands: self._collect_open_api_json() if self.openapi: self.api_commands = _extract_command_from_openapi(self.openapi) def is_alive(self) -> bool: """Returns whether the Lightning App Rest API is available.""" if self.url is None: self._maybe_find_url() if self.url is None: return False resp = requests.get(self.url) return resp.status_code == 200 def _maybe_find_url(self): """Tries to resolve the app url from the provided `app_id_or_name_or_url`.""" if _is_url(self.app_id_or_name_or_url): self.url = self.app_id_or_name_or_url assert self.url return if self.app_id_or_name_or_url is None: url = f"http://localhost:{APP_SERVER_PORT}" resp = requests.get(f"{self.url}/openapi.json") if resp.status_code == 200: self.url = url return app = self._maybe_find_matching_cloud_app() if app: self.url = app.status.url def _maybe_find_matching_cloud_app(self): """Tries to resolve the app url from the provided `app_id_or_name_or_url`.""" client = LightningClient(retry=False) project = _get_project(client) list_apps = client.lightningapp_instance_service_list_lightningapp_instances(project_id=project.project_id) app_names = [_get_app_display_name(lit_app) for lit_app in list_apps.lightningapps] if not self.app_id_or_name_or_url: print(f"ERROR: Provide an application name, id or url with --app_id=X. Found {app_names}") sys.exit(0) for app in list_apps.lightningapps: if app.id == self.app_id_or_name_or_url or _get_app_display_name(app) == self.app_id_or_name_or_url: if app.status.url == "": print("The application is starting. Try in a few moments.") sys.exit(0) return app return None def _collect_open_api_json(self): """This function is used to retrieve the current url associated with an id.""" if _is_url(self.app_id_or_name_or_url): self.url = self.app_id_or_name_or_url assert self.url resp = requests.get(self.url + "/openapi.json") if resp.status_code != 200: print(f"ERROR: The server didn't process the request properly. Found {resp.json()}") sys.exit(0) self.openapi = resp.json() return # 2: If no identifier has been provided, evaluate the local application if self.app_id_or_name_or_url is None: with contextlib.suppress(requests.exceptions.ConnectionError): self.url = f"http://localhost:{APP_SERVER_PORT}" resp = requests.get(f"{self.url}/openapi.json") if resp.status_code != 200: raise Exception(f"The server didn't process the request properly. Found {resp.json()}") self.openapi = resp.json() # 3: If an identified was provided or the local evaluation has failed, evaluate the cloud. else: app = self._maybe_find_matching_cloud_app() if app: if app.status.url == "": raise Exception("The application is starting. Try in a few moments.") resp = requests.get(app.status.url + "/openapi.json") if resp.status_code != 200: raise Exception( "The server didn't process the request properly. " "Try once your application is ready." ) self.url = app.status.url self.openapi = resp.json() self.app_id = app.id self.app_name = _get_app_display_name(app) def _get_project(client: LightningClient, project_id: Optional[str] = None, verbose: bool = True) -> V1Membership: """Get a project membership for the user from the backend.""" if project_id is None: project_id = LIGHTNING_CLOUD_PROJECT_ID if project_id is not None: project = client.projects_service_get_project(project_id) if not project: raise ValueError( "Environment variable `LIGHTNING_CLOUD_PROJECT_ID` is set but could not find an associated project." ) return V1Membership( name=project.name, display_name=project.display_name, description=project.description, created_at=project.created_at, project_id=project.id, owner_id=project.owner_id, owner_type=project.owner_type, quotas=project.quotas, updated_at=project.updated_at, ) projects = client.projects_service_list_memberships() if len(projects.memberships) == 0: raise ValueError("No valid projects found. Please reach out to lightning.ai team to create a project") if len(projects.memberships) > 1 and verbose: print(f"Defaulting to the project: {projects.memberships[0].name}") return projects.memberships[0] def _download_command( command_name: str, cls_path: str, cls_name: str, app_id: Optional[str] = None, debug_mode: bool = False, target_file: Optional[str] = None, ) -> ClientCommand: # TODO: This is a skateboard implementation and the final version will rely on versioned # immutable commands for security concerns command_name = command_name.replace(" ", "_") tmpdir = None if not target_file: tmpdir = osp.join(gettempdir(), f"{getuser()}_commands") makedirs(tmpdir) target_file = osp.join(tmpdir, f"{command_name}.py") if not debug_mode: if app_id: if not os.path.exists(target_file): client = LightningClient(retry=False) project_id = _get_project(client).project_id response = client.lightningapp_instance_service_list_lightningapp_instance_artifacts( project_id=project_id, id=app_id ) for artifact in response.artifacts: if f"commands/{command_name}.py" == artifact.filename: resp = requests.get(artifact.url, allow_redirects=True) with open(target_file, "wb") as f: f.write(resp.content) else: shutil.copy(cls_path, target_file) spec = spec_from_file_location(cls_name, target_file) mod = module_from_spec(spec) sys.modules[cls_name] = mod spec.loader.exec_module(mod) command_type = getattr(mod, cls_name) if issubclass(command_type, ClientCommand): command = command_type(method=None) else: raise ValueError(f"Expected class {cls_name} for command {command_name} to be a `ClientCommand`.") if tmpdir and os.path.exists(tmpdir): shutil.rmtree(tmpdir) return command The provided code snippet includes necessary dependencies for implementing the `connect_app` function. Write a Python function `def connect_app(app_name_or_id: str)` to solve the following problem: Connect your local terminal to a running lightning app. After connecting, the lightning CLI will respond to commands exposed by the app. Example: \b # connect to an app named pizza-cooker-123 lightning connect pizza-cooker-123 \b # this will now show the commands exposed by pizza-cooker-123 lightning --help \b # while connected, you can run the cook-pizza command exposed # by pizza-cooker-123.BTW, this should arguably generate an exception :-) lightning cook-pizza --flavor pineapple \b # once done, disconnect and go back to the standard lightning CLI commands lightning disconnect Here is the function: def connect_app(app_name_or_id: str): """Connect your local terminal to a running lightning app. After connecting, the lightning CLI will respond to commands exposed by the app. Example: \b # connect to an app named pizza-cooker-123 lightning connect pizza-cooker-123 \b # this will now show the commands exposed by pizza-cooker-123 lightning --help \b # while connected, you can run the cook-pizza command exposed # by pizza-cooker-123.BTW, this should arguably generate an exception :-) lightning cook-pizza --flavor pineapple \b # once done, disconnect and go back to the standard lightning CLI commands lightning disconnect """ from lightning.app.utilities.commands.base import _download_command _clean_lightning_connection() if not os.path.exists(_LIGHTNING_CONNECTION_FOLDER): os.makedirs(_LIGHTNING_CONNECTION_FOLDER) connected_file = os.path.join(_LIGHTNING_CONNECTION_FOLDER, "connect.txt") matched_connection_path = _scan_lightning_connections(app_name_or_id) if os.path.exists(connected_file): with open(connected_file) as f: result = f.readlines()[0].replace("\n", "") if result == app_name_or_id: if app_name_or_id == "localhost": click.echo("You are connected to the local Lightning App.") else: click.echo(f"You are already connected to the cloud Lightning App: {app_name_or_id}.") else: disconnect_app() connect_app(app_name_or_id) elif app_name_or_id.startswith("localhost"): with Progress() as progress_bar: connecting = progress_bar.add_task("[magenta]Setting things up for you...", total=1.0) if app_name_or_id != "localhost": raise Exception("You need to pass localhost to connect to the local Lightning App.") retriever = _LightningAppOpenAPIRetriever(None) if retriever.api_commands is None: raise Exception(f"Connection wasn't successful. Is your app {app_name_or_id} running?") increment = 1 / (1 + len(retriever.api_commands)) progress_bar.update(connecting, advance=increment) commands_folder = os.path.join(_LIGHTNING_CONNECTION_FOLDER, "commands") if not os.path.exists(commands_folder): os.makedirs(commands_folder) _write_commands_metadata(retriever.api_commands) with open(os.path.join(commands_folder, "openapi.json"), "w") as f: json.dump(retriever.openapi, f) _install_missing_requirements(retriever) for command_name, metadata in retriever.api_commands.items(): if "cls_path" in metadata: target_file = os.path.join(commands_folder, f"{command_name.replace(' ', '_')}.py") _download_command( command_name, metadata["cls_path"], metadata["cls_name"], None, target_file=target_file, ) else: with open(os.path.join(commands_folder, f"{command_name}.txt"), "w") as f: f.write(command_name) progress_bar.update(connecting, advance=increment) with open(connected_file, "w") as f: f.write(app_name_or_id + "\n") click.echo("The lightning App CLI now responds to app commands. Use 'lightning_app --help' to see them.") click.echo(" ") Popen( f"LIGHTNING_CONNECT_PPID={_PPID} {sys.executable} -m lightning_app --help", shell=True, stdout=sys.stdout, stderr=sys.stderr, ).wait() elif matched_connection_path: matched_connected_file = os.path.join(matched_connection_path, "connect.txt") matched_commands = os.path.join(matched_connection_path, "commands") if os.path.isdir(matched_commands): commands = os.path.join(_LIGHTNING_CONNECTION_FOLDER, "commands") shutil.copytree(matched_commands, commands) shutil.copy(matched_connected_file, connected_file) click.echo("The lightning App CLI now responds to app commands. Use 'lightning_app --help' to see them.") click.echo(" ") Popen( f"LIGHTNING_CONNECT_PPID={_PPID} {sys.executable} -m lightning_app --help", shell=True, stdout=sys.stdout, stderr=sys.stderr, ).wait() else: with Progress() as progress_bar: connecting = progress_bar.add_task("[magenta]Setting things up for you...", total=1.0) retriever = _LightningAppOpenAPIRetriever(app_name_or_id) if not retriever.api_commands: client = LightningClient(retry=False) project = _get_project(client) apps = client.lightningapp_instance_service_list_lightningapp_instances(project_id=project.project_id) click.echo( "We didn't find a matching App. Here are the available Apps that you can " f"connect to {[_get_app_display_name(app) for app in apps.lightningapps]}." ) return increment = 1 / (1 + len(retriever.api_commands)) progress_bar.update(connecting, advance=increment) _install_missing_requirements(retriever) commands_folder = os.path.join(_LIGHTNING_CONNECTION_FOLDER, "commands") if not os.path.exists(commands_folder): os.makedirs(commands_folder) _write_commands_metadata(retriever.api_commands) for command_name, metadata in retriever.api_commands.items(): if "cls_path" in metadata: target_file = os.path.join(commands_folder, f"{command_name}.py") _download_command( command_name, metadata["cls_path"], metadata["cls_name"], retriever.app_id, target_file=target_file, ) else: with open(os.path.join(commands_folder, f"{command_name}.txt"), "w") as f: f.write(command_name) progress_bar.update(connecting, advance=increment) with open(connected_file, "w") as f: f.write(retriever.app_name + "\n") f.write(retriever.app_id + "\n") click.echo("The lightning App CLI now responds to app commands. Use 'lightning_app --help' to see them.") click.echo(" ") Popen( f"LIGHTNING_CONNECT_PPID={_PPID} {sys.executable} -m lightning_app --help", shell=True, stdout=sys.stdout, stderr=sys.stderr, ).wait()
Connect your local terminal to a running lightning app. After connecting, the lightning CLI will respond to commands exposed by the app. Example: \b # connect to an app named pizza-cooker-123 lightning connect pizza-cooker-123 \b # this will now show the commands exposed by pizza-cooker-123 lightning --help \b # while connected, you can run the cook-pizza command exposed # by pizza-cooker-123.BTW, this should arguably generate an exception :-) lightning cook-pizza --flavor pineapple \b # once done, disconnect and go back to the standard lightning CLI commands lightning disconnect
155,680
import json import os import shutil import sys from subprocess import Popen from typing import List, Optional, Tuple import click import psutil from lightning_utilities.core.imports import package_available from rich.progress import Progress from lightning.app.utilities.cli_helpers import _get_app_display_name, _LightningAppOpenAPIRetriever from lightning.app.utilities.cloud import _get_project from lightning.app.utilities.enum import OpenAPITags from lightning.app.utilities.log import get_logfile from lightning.app.utilities.network import LightningClient _LIGHTNING_CONNECTION_FOLDER = os.path.join(_LIGHTNING_CONNECTION, _PPID) def _read_connected_file(connected_file): if os.path.exists(connected_file): with open(connected_file) as f: lines = [line.replace("\n", "") for line in f.readlines()] if len(lines) == 2: return lines[0], lines[1] return lines[0], None return None, None def _retrieve_connection_to_an_app() -> Tuple[Optional[str], Optional[str]]: connected_file = os.path.join(_LIGHTNING_CONNECTION_FOLDER, "connect.txt") return _read_connected_file(connected_file)
null
155,681
import json import os import shutil import sys from subprocess import Popen from typing import List, Optional, Tuple import click import psutil from lightning_utilities.core.imports import package_available from rich.progress import Progress from lightning.app.utilities.cli_helpers import _get_app_display_name, _LightningAppOpenAPIRetriever from lightning.app.utilities.cloud import _get_project from lightning.app.utilities.enum import OpenAPITags from lightning.app.utilities.log import get_logfile from lightning.app.utilities.network import LightningClient def _get_commands_metadata(): metadata_path = os.path.join(_get_commands_folder(), ".meta.json") with open(metadata_path) as f: return json.load(f) def _list_app_commands(echo: bool = True) -> List[str]: metadata = _get_commands_metadata() metadata = {key.replace("_", " "): value for key, value in metadata.items()} command_names = sorted(metadata.keys()) if not command_names: click.echo("The current Lightning App doesn't have commands.") return [] app_info = metadata[command_names[0]].get("app_info", None) title, description, on_connect_end = "Lightning", None, None if app_info: title = app_info.get("title") description = app_info.get("description") on_connect_end = app_info.get("on_connect_end") if echo: click.echo(f"{title} App") if description: click.echo("") click.echo("Description:") if description.endswith("\n"): description = description[:-2] click.echo(f" {description}") click.echo("") click.echo("Commands:") max_length = max(len(n) for n in command_names) for command_name in command_names: padding = (max_length + 1 - len(command_name)) * " " click.echo(f" {command_name}{padding}{metadata[command_name].get('description', '')}") if "LIGHTNING_CONNECT_PPID" in os.environ and on_connect_end: if on_connect_end.endswith("\n"): on_connect_end = on_connect_end[:-2] click.echo(on_connect_end) return command_names
null
155,682
import ast import sys import click import lightning_cloud import rich from rich.live import Live from rich.spinner import Spinner from rich.text import Text from lightning.app.utilities.app_helpers import Logger from lightning.app.utilities.cli_helpers import _error_and_exit from lightning.app.utilities.cloud import _get_project from lightning.app.utilities.network import LightningClient def _error_and_exit(msg: str) -> None: rich.print(f"[red]ERROR[/red]: {msg}") sys.exit(0) def _get_project(client: LightningClient, project_id: Optional[str] = None, verbose: bool = True) -> V1Membership: """Get a project membership for the user from the backend.""" if project_id is None: project_id = LIGHTNING_CLOUD_PROJECT_ID if project_id is not None: project = client.projects_service_get_project(project_id) if not project: raise ValueError( "Environment variable `LIGHTNING_CLOUD_PROJECT_ID` is set but could not find an associated project." ) return V1Membership( name=project.name, display_name=project.display_name, description=project.description, created_at=project.created_at, project_id=project.id, owner_id=project.owner_id, owner_type=project.owner_type, quotas=project.quotas, updated_at=project.updated_at, ) projects = client.projects_service_list_memberships() if len(projects.memberships) == 0: raise ValueError("No valid projects found. Please reach out to lightning.ai team to create a project") if len(projects.memberships) > 1 and verbose: print(f"Defaulting to the project: {projects.memberships[0].name}") return projects.memberships[0] The provided code snippet includes necessary dependencies for implementing the `connect_data` function. Write a Python function `def connect_data( name: str, region: str, source: str, secret_arn_name: str = "", destination: str = "", project_name: str = "", ) -> None` to solve the following problem: Create a new data connection. Here is the function: def connect_data( name: str, region: str, source: str, secret_arn_name: str = "", destination: str = "", project_name: str = "", ) -> None: """Create a new data connection.""" from lightning_cloud.openapi import Create, V1AwsDataConnection if sys.platform == "win32": _error_and_exit("Data connection isn't supported on windows. Open an issue on Github.") with Live(Spinner("point", text=Text("pending...", style="white")), transient=True) as live: live.stop() client = LightningClient(retry=False) projects = client.projects_service_list_memberships() project_id = None for project in projects.memberships: if project.name == project_name: project_id = project.project_id break if project_id is None: project_id = _get_project(client).project_id if not source.startswith("s3://"): return _error_and_exit( "Only public S3 folders are supported for now. Please, open a Github issue with your use case." ) try: client.data_connection_service_create_data_connection( body=Create( name=name, aws=V1AwsDataConnection( region=region, source=source, destination=destination, secret_arn_name=secret_arn_name, ), ), project_id=project_id, ) # Note: Expose through lightning show data {DATA_NAME} # response = client.data_connection_service_list_data_connection_artifacts( # project_id=project_id, # id=response.id, # ) except lightning_cloud.openapi.rest.ApiException as e: message = ast.literal_eval(e.body.decode("utf-8"))["message"] _error_and_exit(f"The data connection creation failed. Message: {message}") rich.print(f"[green]Succeeded[/green]: You have created a new data connection {name}.") return None
Create a new data connection.
155,683
from typing import Any import click from lightning.app.cli.cmd_apps import _AppManager The provided code snippet includes necessary dependencies for implementing the `get_list` function. Write a Python function `def get_list() -> None` to solve the following problem: List Lightning AI self-managed resources (e.g. apps) Here is the function: def get_list() -> None: """List Lightning AI self-managed resources (e.g. apps)""" pass
List Lightning AI self-managed resources (e.g. apps)
155,684
from typing import Any import click from lightning.app.cli.cmd_apps import _AppManager class _AppManager: """_AppManager implements API calls specific to Lightning AI BYOC apps.""" def __init__(self) -> None: self.api_client = LightningClient(retry=False) def get_app(self, app_id: str) -> Externalv1LightningappInstance: project = _get_project(self.api_client) return self.api_client.lightningapp_instance_service_get_lightningapp_instance( project_id=project.project_id, id=app_id ) def list_apps(self, limit: int = 100, phase_in: Optional[List[str]] = None) -> List[Externalv1LightningappInstance]: phase_in = phase_in or [] project = _get_project(self.api_client) kwargs = { "project_id": project.project_id, "limit": limit, "phase_in": phase_in, } resp = self.api_client.lightningapp_instance_service_list_lightningapp_instances(**kwargs) apps = resp.lightningapps while resp.next_page_token is not None and resp.next_page_token != "": kwargs["page_token"] = resp.next_page_token resp = self.api_client.lightningapp_instance_service_list_lightningapp_instances(**kwargs) apps = apps + resp.lightningapps return apps def list_components(self, app_id: str, phase_in: Optional[List[str]] = None) -> List[Externalv1Lightningwork]: phase_in = phase_in or [] project = _get_project(self.api_client) resp = self.api_client.lightningwork_service_list_lightningwork( project_id=project.project_id, app_id=app_id, phase_in=phase_in, ) return resp.lightningworks def list(self, limit: int = 100) -> None: console = Console() console.print(_AppList(self.list_apps(limit=limit)).as_table()) def delete(self, app_id: str) -> None: project = _get_project(self.api_client) self.api_client.lightningapp_instance_service_delete_lightningapp_instance( project_id=project.project_id, id=app_id, ) The provided code snippet includes necessary dependencies for implementing the `list_apps` function. Write a Python function `def list_apps(**kwargs: Any) -> None` to solve the following problem: List your Lightning AI apps. Here is the function: def list_apps(**kwargs: Any) -> None: """List your Lightning AI apps.""" app_manager = _AppManager() app_manager.list()
List your Lightning AI apps.
155,685
import click import inquirer from inquirer.themes import GreenPassion from rich.console import Console from lightning.app.cli.cmd_apps import _AppManager def delete() -> None: """Delete Lightning AI self-managed resources (e.g. apps)""" pass def _find_selected_app_instance_id(app_name: str) -> str: console = Console() app_manager = _AppManager() all_app_names_and_ids = {} selected_app_instance_id = None for app in app_manager.list_apps(): all_app_names_and_ids[app.name] = app.id # figure out the ID of some app_name if app_name == app.name or app_name == app.id: selected_app_instance_id = app.id break if selected_app_instance_id is None: # when there is no app with the given app_name, # ask the user which app they would like to delete. console.print(f'[b][yellow]Cannot find app named "{app_name}"[/yellow][/b]') try: ask = [ inquirer.List( "app_name", message="Select the app name to delete", choices=list(all_app_names_and_ids.keys()), ), ] app_name = inquirer.prompt(ask, theme=GreenPassion(), raise_keyboard_interrupt=True)["app_name"] selected_app_instance_id = all_app_names_and_ids[app_name] except KeyboardInterrupt: console.print("[b][red]Cancelled by user![/b][/red]") raise InterruptedError return selected_app_instance_id def _delete_app_confirmation_prompt(app_name: str) -> None: console = Console() # when the --yes / -y flags were not passed, do a final # confirmation that the user wants to delete the app. try: ask = [ inquirer.Confirm( "confirm", message=f'Are you sure you want to delete app "{app_name}""?', default=False, ), ] if inquirer.prompt(ask, theme=GreenPassion(), raise_keyboard_interrupt=True)["confirm"] is False: console.print("[b][red]Aborted![/b][/red]") raise InterruptedError except KeyboardInterrupt: console.print("[b][red]Cancelled by user![/b][/red]") raise InterruptedError "skip_user_confirm_prompt", "--yes", "-y", is_flag=True, default=False, help="Do not prompt for confirmation.", class _AppManager: """_AppManager implements API calls specific to Lightning AI BYOC apps.""" def __init__(self) -> None: self.api_client = LightningClient(retry=False) def get_app(self, app_id: str) -> Externalv1LightningappInstance: project = _get_project(self.api_client) return self.api_client.lightningapp_instance_service_get_lightningapp_instance( project_id=project.project_id, id=app_id ) def list_apps(self, limit: int = 100, phase_in: Optional[List[str]] = None) -> List[Externalv1LightningappInstance]: phase_in = phase_in or [] project = _get_project(self.api_client) kwargs = { "project_id": project.project_id, "limit": limit, "phase_in": phase_in, } resp = self.api_client.lightningapp_instance_service_list_lightningapp_instances(**kwargs) apps = resp.lightningapps while resp.next_page_token is not None and resp.next_page_token != "": kwargs["page_token"] = resp.next_page_token resp = self.api_client.lightningapp_instance_service_list_lightningapp_instances(**kwargs) apps = apps + resp.lightningapps return apps def list_components(self, app_id: str, phase_in: Optional[List[str]] = None) -> List[Externalv1Lightningwork]: phase_in = phase_in or [] project = _get_project(self.api_client) resp = self.api_client.lightningwork_service_list_lightningwork( project_id=project.project_id, app_id=app_id, phase_in=phase_in, ) return resp.lightningworks def list(self, limit: int = 100) -> None: console = Console() console.print(_AppList(self.list_apps(limit=limit)).as_table()) def delete(self, app_id: str) -> None: project = _get_project(self.api_client) self.api_client.lightningapp_instance_service_delete_lightningapp_instance( project_id=project.project_id, id=app_id, ) The provided code snippet includes necessary dependencies for implementing the `delete_app` function. Write a Python function `def delete_app(app_name: str, skip_user_confirm_prompt: bool) -> None` to solve the following problem: Delete a Lightning app. Deleting an app also deletes all app websites, works, artifacts, and logs. This permanently removes any record of the app as well as all any of its associated resources and data. This does not affect any resources and data associated with other Lightning apps on your account. Here is the function: def delete_app(app_name: str, skip_user_confirm_prompt: bool) -> None: """Delete a Lightning app. Deleting an app also deletes all app websites, works, artifacts, and logs. This permanently removes any record of the app as well as all any of its associated resources and data. This does not affect any resources and data associated with other Lightning apps on your account. """ console = Console() try: selected_app_instance_id = _find_selected_app_instance_id(app_name=app_name) if not skip_user_confirm_prompt: _delete_app_confirmation_prompt(app_name=app_name) except InterruptedError: return try: # Delete the app! app_manager = _AppManager() app_manager.delete(app_id=selected_app_instance_id) except Exception as ex: console.print( f'[b][red]An issue occurred while deleting app "{app_name}. If the issue persists, please ' "reach out to us at [link=mailto:support@lightning.ai]support@lightning.ai[/link][/b][/red]." ) raise click.ClickException(str(ex)) console.print(f'[b][green]App "{app_name}" has been successfully deleted"![/green][/b]') return
Delete a Lightning app. Deleting an app also deletes all app websites, works, artifacts, and logs. This permanently removes any record of the app as well as all any of its associated resources and data. This does not affect any resources and data associated with other Lightning apps on your account.
155,686
import os import re import shutil import subprocess import sys from typing import Dict, Optional, Tuple import click import requests from packaging.version import Version from lightning.app.core.constants import LIGHTNING_APPS_PUBLIC_REGISTRY, LIGHTNING_COMPONENT_PUBLIC_REGISTRY from lightning.app.utilities.app_helpers import Logger The provided code snippet includes necessary dependencies for implementing the `install` function. Write a Python function `def install() -> None` to solve the following problem: Install Lightning AI selfresources. Here is the function: def install() -> None: """Install Lightning AI selfresources.""" pass
Install Lightning AI selfresources.
155,687
import os import re import shutil import subprocess import sys from typing import Dict, Optional, Tuple import click import requests from packaging.version import Version from lightning.app.core.constants import LIGHTNING_APPS_PUBLIC_REGISTRY, LIGHTNING_COMPONENT_PUBLIC_REGISTRY from lightning.app.utilities.app_helpers import Logger def _install_app_command(name: str, yes: bool, version: str, overwrite: bool = False) -> None: def install_app(name: str, yes: bool, version: str, overwrite: bool = False) -> None: _install_app_command(name, yes, version, overwrite=overwrite)
null
155,688
import os import re import shutil import subprocess import sys from typing import Dict, Optional, Tuple import click import requests from packaging.version import Version from lightning.app.core.constants import LIGHTNING_APPS_PUBLIC_REGISTRY, LIGHTNING_COMPONENT_PUBLIC_REGISTRY from lightning.app.utilities.app_helpers import Logger def _install_component_command(name: str, yes: bool, version: str, overwrite: bool = False) -> None: def install_component(name: str, yes: bool, version: str) -> None: _install_component_command(name, yes, version)
null
155,689
import os import re import shutil import subprocess import sys from typing import Dict, Optional, Tuple import click import requests from packaging.version import Version from lightning.app.core.constants import LIGHTNING_APPS_PUBLIC_REGISTRY, LIGHTNING_COMPONENT_PUBLIC_REGISTRY from lightning.app.utilities.app_helpers import Logger logger = Logger(__name__) import os ) ) "checkpoint_folder", ) "--output_file", ) """Set the environment variables for the new processes. The Fabric connector will parse the arguments set here. """ os.environ["LT_CLI_USED"] = "1" os.environ["LT_DEVICES"] = str(args.devices) os.environ["LT_NUM_NODES"] = str(args.num_nodes) def _install_with_env(repo_url: str, folder_name: str, cwd: Optional[str] = None) -> None: if not cwd: cwd = os.getcwd() # clone repo logger.info(f"⚡ RUN: git clone {repo_url}") subprocess.call(["git", "clone", repo_url]) # step into the repo folder os.chdir(f"{folder_name}") cwd = os.getcwd() # create env logger.info(f"⚡ CREATE: virtual env at {cwd}") subprocess.call(["python", "-m", "venv", cwd]) # activate and install reqs # TODO: remove shell=True... but need to run command in venv logger.info("⚡ RUN: install requirements (pip install -r requirements.txt)") subprocess.call("source bin/activate && pip install -r requirements.txt", shell=True) # install project # TODO: remove shell=True... but need to run command in venv logger.info("⚡ RUN: setting up project (pip install -e .)") subprocess.call("source bin/activate && pip install -e .", shell=True) m = f""" ⚡ Installed! ⚡ to use your app go into the folder: cd {folder_name} activate the environment: source bin/activate run the app: lightning run app [the_app_file.py] """ logger.info(m)
null
155,690
import abc import asyncio import base64 import os import platform from typing import TYPE_CHECKING, Any, Dict, Optional import requests import uvicorn from fastapi import FastAPI from lightning_utilities.core.imports import compare_version, module_available from pydantic import BaseModel from lightning.app.core.work import LightningWork from lightning.app.utilities.app_helpers import Logger from lightning.app.utilities.imports import _is_torch_available, requires def _get_device(): import operator import torch _TORCH_GREATER_EQUAL_1_12 = compare_version("torch", operator.ge, "1.12.0") local_rank = int(os.getenv("LOCAL_RANK", "0")) if _TORCH_GREATER_EQUAL_1_12 and torch.backends.mps.is_available() and platform.processor() in ("arm", "arm64"): return torch.device("mps", local_rank) return torch.device(f"cuda:{local_rank}" if torch.cuda.is_available() else "cpu")
null
155,691
import asyncio import logging import time import uuid from itertools import cycle from typing import Any, Dict, List, Optional, Tuple, Type, Union from typing import SupportsFloat as Numeric import requests import uvicorn from fastapi import FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import RedirectResponse from pydantic import BaseModel from starlette.staticfiles import StaticFiles from lightning.app.components.serve.cold_start_proxy import ColdStartProxy from lightning.app.core.flow import LightningFlow from lightning.app.core.work import LightningWork from lightning.app.utilities.app_helpers import Logger from lightning.app.utilities.cloud import is_running_in_cloud from lightning.app.utilities.imports import _is_aiohttp_available, requires from lightning.app.utilities.packaging.cloud_compute import CloudCompute The provided code snippet includes necessary dependencies for implementing the `_maybe_raise_granular_exception` function. Write a Python function `def _maybe_raise_granular_exception(exception: Exception) -> None` to solve the following problem: Handle an exception from hitting the model servers. Here is the function: def _maybe_raise_granular_exception(exception: Exception) -> None: """Handle an exception from hitting the model servers.""" if not isinstance(exception, Exception): return if isinstance(exception, HTTPException): raise exception if isinstance(exception, aiohttp.client_exceptions.ServerDisconnectedError): raise HTTPException(500, "Worker Server Disconnected") from exception if isinstance(exception, aiohttp.client_exceptions.ClientError): logging.exception(exception) raise HTTPException(500, "Worker Server error") from exception if isinstance(exception, asyncio.TimeoutError): raise HTTPException(408, "Request timed out") from exception if isinstance(exception, Exception) and exception.args[0] == "Server disconnected": raise HTTPException(500, "Worker Server disconnected") from exception logging.exception(exception) raise HTTPException(500, exception.args[0]) from exception
Handle an exception from hitting the model servers.
155,692
import asyncio import logging import time import uuid from itertools import cycle from typing import Any, Dict, List, Optional, Tuple, Type, Union from typing import SupportsFloat as Numeric import requests import uvicorn from fastapi import FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import RedirectResponse from pydantic import BaseModel from starlette.staticfiles import StaticFiles from lightning.app.components.serve.cold_start_proxy import ColdStartProxy from lightning.app.core.flow import LightningFlow from lightning.app.core.work import LightningWork from lightning.app.utilities.app_helpers import Logger from lightning.app.utilities.cloud import is_running_in_cloud from lightning.app.utilities.imports import _is_aiohttp_available, requires from lightning.app.utilities.packaging.cloud_compute import CloudCompute class _TrackableFastAPI(FastAPI): """A FastAPI subclass that tracks the request metadata.""" def __init__(self, *args: Any, **kwargs: Any): super().__init__(*args, **kwargs) self.global_request_count = 0 self.num_current_requests = 0 self.last_processing_time = 0 def _create_fastapi(title: str) -> _TrackableFastAPI: fastapi_app = _TrackableFastAPI(title=title) fastapi_app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @fastapi_app.get("/", include_in_schema=False) async def docs(): return RedirectResponse("/docs") @fastapi_app.get("/num-requests") async def num_requests() -> int: return fastapi_app.num_current_requests return fastapi_app
null
155,693
import abc import inspect import os import pydoc import subprocess import sys from typing import Any, Callable, Optional import fastapi import uvicorn from fastapi import FastAPI from fastapi.responses import JSONResponse from lightning.app.components.serve.types import _DESERIALIZER, _SERIALIZER from lightning.app.core.work import LightningWork from lightning.app.utilities.app_helpers import Logger class ModelInferenceAPI(LightningWork, abc.ABC): def __init__( self, input: Optional[str] = None, output: Optional[str] = None, host: str = "127.0.0.1", port: int = 7777, workers: int = 0, ): """The ModelInferenceAPI Class enables to easily get your model served. Arguments: input: Optional `input` to be provided. This would make provide a built-in deserializer. output: Optional `output` to be provided. This would make provide a built-in serializer. host: Address to be used to serve the model. port: Port to be used to serve the model. workers: Number of workers for the uvicorn. Warning, this won't work if your subclass takes more arguments. """ super().__init__(parallel=True, host=host, port=port) if input and input not in _DESERIALIZER: raise Exception(f"Only input in {_DESERIALIZER.keys()} are supported.") if output and output not in _SERIALIZER: raise Exception(f"Only output in {_SERIALIZER.keys()} are supported.") self.input = input self.output = output self.workers = workers self._model = None self.ready = False def model(self): return self._model def build_model(self) -> Any: """Override to define your model.""" def deserialize(self, data) -> Any: return data def predict(self, data) -> Any: """Override to add your predict logic.""" def serialize(self, data) -> Any: return data def run(self): global fastapi_service if self.workers > 1: # TODO: This is quite limitated # Find a more reliable solution to enable multi workers serving. env = os.environ.copy() module = inspect.getmodule(self).__file__ env["LIGHTNING_MODEL_INFERENCE_API_FILE"] = module env["LIGHTNING_MODEL_INFERENCE_API_CLASS_NAME"] = self.__class__.__name__ if self.input: env["LIGHTNING_MODEL_INFERENCE_API_INPUT"] = self.input if self.output: env["LIGHTNING_MODEL_INFERENCE_API_OUTPUT"] = self.output command = [ sys.executable, "-m", "uvicorn", "--workers", str(self.workers), "--host", str(self.host), "--port", str(self.port), "serve:fastapi_service", ] process = subprocess.Popen(command, env=env, cwd=os.path.dirname(__file__)) self.ready = True process.wait() else: self._populate_app(fastapi_service) self.ready = True self._launch_server(fastapi_service) def _populate_app(self, fastapi_service: FastAPI): self._model = self.build_model() fastapi_service.post("/predict", response_class=JSONResponse)( _InferenceCallable( deserialize=_DESERIALIZER[self.input] if self.input else self.deserialize, predict=self.predict, serialize=_SERIALIZER[self.output] if self.output else self.serialize, ).run ) def _launch_server(self, fastapi_service: FastAPI): logger.info(f"Your app has started. View it in your browser: http://{self.host}:{self.port}") uvicorn.run(app=fastapi_service, host=self.host, port=self.port, log_level="error") def configure_layout(self) -> str: return f"{self.url}/docs" The provided code snippet includes necessary dependencies for implementing the `_maybe_create_instance` function. Write a Python function `def _maybe_create_instance() -> Optional[ModelInferenceAPI]` to solve the following problem: This function tries to re-create the user `ModelInferenceAPI` if the environment associated with multi workers are present. Here is the function: def _maybe_create_instance() -> Optional[ModelInferenceAPI]: """This function tries to re-create the user `ModelInferenceAPI` if the environment associated with multi workers are present.""" render_fn_name = os.getenv("LIGHTNING_MODEL_INFERENCE_API_CLASS_NAME", None) render_fn_module_file = os.getenv("LIGHTNING_MODEL_INFERENCE_API_FILE", None) if render_fn_name is None or render_fn_module_file is None: return None module = pydoc.importfile(render_fn_module_file) cls = getattr(module, render_fn_name) input = os.getenv("LIGHTNING_MODEL_INFERENCE_API_INPUT", None) output = os.getenv("LIGHTNING_MODEL_INFERENCE_API_OUTPUT", None) return cls(input=input, output=output)
This function tries to re-create the user `ModelInferenceAPI` if the environment associated with multi workers are present.
155,694
import abc import inspect import os import pydoc import subprocess import sys from typing import Any, Callable, Type from lightning.app.core.work import LightningWork from lightning.app.utilities.app_helpers import StreamLitStatePlugin from lightning.app.utilities.state import AppState class _PatchedWork: """The ``_PatchedWork`` is used to emulate a work instance from a subprocess. This is acheived by patching the self reference in methods an properties to point to the AppState. Args: state: The work state to patch work_class: The work class to emulate """ def __init__(self, state: AppState, work_class: Type): super().__init__() self._state = state self._work_class = work_class def __getattr__(self, name: str) -> Any: try: return getattr(self._state, name) except AttributeError: # The name isn't in the state, so check if it's a callable or a property attribute = inspect.getattr_static(self._work_class, name) if callable(attribute): attribute = attribute.__get__(self, self._work_class) return attribute if isinstance(attribute, (staticmethod, property)): return attribute.__get__(self, self._work_class) # Look for the name in the instance (e.g. for private variables) return object.__getattribute__(self, name) def __setattr__(self, name: str, value: Any) -> None: if name in ["_state", "_work_class"]: return object.__setattr__(self, name, value) if hasattr(self._state, name): return setattr(self._state, name, value) return object.__setattr__(self, name, value) def _reduce_to_component_scope(state: AppState, component_name: str) -> AppState: """Given the app state, this utility traverses down to the level of the given component name.""" component_name_parts = component_name.split(".")[1:] # exclude root component_state = state for part in component_name_parts: component_state = getattr(component_state, part) return component_state def _get_work_class() -> Callable: """Import the work class specified in the environment.""" work_name = os.environ["LIGHTNING_WORK"] work_module_file = os.environ["LIGHTNING_WORK_MODULE_FILE"] module = pydoc.importfile(work_module_file) return getattr(module, work_name) def _build_model(work: ServeStreamlit) -> None: import streamlit as st # Build the model (once per session, equivalent to gradio when enable_queue is Flase) if "_model" not in st.session_state: with st.spinner("Building model..."): st.session_state["_model"] = work.build_model() work._model = st.session_state["_model"] class StreamLitStatePlugin(BaseStatePlugin): def __init__(self): super().__init__() import streamlit as st if hasattr(st, "session_state") and "websocket_thread" not in st.session_state: thread = threading.Thread(target=target_fn) st.session_state.websocket_thread = thread thread.setDaemon(True) thread.start() def should_update_app(self, deep_diff): return deep_diff def get_context(self): return {"type": AppStateType.DEFAULT.value} def render_non_authorized(self): pass class AppState: _APP_PRIVATE_KEYS: Tuple[str, ...] = ( "_use_localhost", "_host", "_session_id", "_state", "_last_state", "_url", "_port", "_request_state", "_store_state", "_send_state", "_my_affiliation", "_find_state_under_affiliation", "_plugin", "_attach_plugin", "_authorized", "is_authorized", "_debug", "_session", ) _MY_AFFILIATION: Tuple[str, ...] = () def __init__( self, host: Optional[str] = None, port: Optional[int] = None, last_state: Optional[Dict] = None, state: Optional[Dict] = None, my_affiliation: Tuple[str, ...] = None, plugin: Optional[BaseStatePlugin] = None, ) -> None: """The AppState class enables Frontend users to interact with their application state. When the state isn't defined, it would be pulled from the app REST API Server. If the state gets modified by the user, the new state would be sent to the API Server. Arguments: host: Rest API Server current host port: Rest API Server current port last_state: The state pulled on first access. state: The state modified by the user. my_affiliation: A tuple describing the affiliation this app state represents. When storing a state dict on this AppState, this affiliation will be used to reduce the scope of the given state. plugin: A plugin to handle authorization. """ self._use_localhost = "LIGHTNING_APP_STATE_URL" not in os.environ self._host = host or ("http://127.0.0.1" if self._use_localhost else None) self._port = port or (APP_SERVER_PORT if self._use_localhost else None) self._last_state = last_state self._state = state self._session_id = "1234" self._my_affiliation = my_affiliation if my_affiliation is not None else AppState._MY_AFFILIATION self._authorized = None self._attach_plugin(plugin) self._session = self._configure_session() def _url(self) -> str: if self._host is None: app_ip = "" if "LIGHTNING_CLOUD_PROJECT_ID" in os.environ and "LIGHTNING_CLOUD_APP_ID" in os.environ: client = LightningClient() app_instance = client.lightningapp_instance_service_get_lightningapp_instance( os.environ.get("LIGHTNING_CLOUD_PROJECT_ID"), os.environ.get("LIGHTNING_CLOUD_APP_ID"), ) app_ip = app_instance.status.ip_address # TODO: Don't hard code port 8080 here self._host = f"http://{app_ip}:8080" if app_ip else APP_SERVER_HOST return f"{self._host}:{self._port}" if self._use_localhost else self._host def _attach_plugin(self, plugin: Optional[BaseStatePlugin]) -> None: plugin = plugin if plugin is not None else AppStatePlugin() self._plugin = plugin def _find_state_under_affiliation(state, my_affiliation: Tuple[str, ...]) -> Dict[str, Any]: """This method is used to extract the subset of the app state associated with the given affiliation. For example, if the affiliation is ``("root", "subflow")``, then the returned state will be ``state["flows"]["subflow"]``. """ children_state = state for name in my_affiliation: if name in children_state["flows"]: children_state = children_state["flows"][name] elif name in children_state["works"]: children_state = children_state["works"][name] else: raise ValueError(f"Failed to extract the state under the affiliation '{my_affiliation}'.") return children_state def _store_state(self, state: Dict[str, Any]) -> None: # Relying on the global variable to ensure the # deep_diff is done on the entire state. global _LAST_STATE global _STATE _LAST_STATE = deepcopy(state) _STATE = state # If the affiliation is passed, the AppState was created in a LightningFlow context. # The state should be only the one of this LightningFlow and its children. self._last_state = self._find_state_under_affiliation(_LAST_STATE, self._my_affiliation) self._state = self._find_state_under_affiliation(_STATE, self._my_affiliation) def send_delta(self) -> None: app_url = f"{self._url}/api/v1/delta" deep_diff = DeepDiff(_LAST_STATE, _STATE, verbose_level=2) assert self._plugin is not None # TODO: Find how to prevent the infinite loop on refresh without storing the DeepDiff if self._plugin.should_update_app(deep_diff): data = {"delta": json.loads(deep_diff.to_json())} headers = headers_for(self._plugin.get_context()) try: # TODO: Send the delta directly to the REST API. response = self._session.post(app_url, json=data, headers=headers) except ConnectionError as ex: raise AttributeError("Failed to connect and send the app state. Is the app running?") from ex if response and response.status_code != 200: raise Exception(f"The response from the server was {response.status_code}. Your inputs were rejected.") def _request_state(self) -> None: if self._state is not None: return app_url = f"{self._url}/api/v1/state" headers = headers_for(self._plugin.get_context()) if self._plugin else {} response_json = {} # Sometimes the state URL can return an empty JSON when things are being set-up, # so we wait for it to be ready here. while response_json == {}: sleep(0.5) try: response = self._session.get(app_url, headers=headers, timeout=1) except ConnectionError as ex: raise AttributeError("Failed to connect and fetch the app state. Is the app running?") from ex self._authorized = response.status_code if self._authorized != 200: return response_json = response.json() logger.debug(f"GET STATE {response} {response_json}") self._store_state(response_json) def __getattr__(self, name: str) -> Union[Any, "AppState"]: if name in self._APP_PRIVATE_KEYS: return object.__getattr__(self, name) # The state needs to be fetched on access if it doesn't exist. self._request_state() if name in self._state.get("vars", {}): value = self._state["vars"][name] if isinstance(value, dict): return _maybe_create_drive("root." + ".".join(self._my_affiliation), value) return value if name in self._state.get("works", {}): return AppState( self._host, self._port, last_state=self._last_state["works"][name], state=self._state["works"][name] ) if name in self._state.get("flows", {}): return AppState( self._host, self._port, last_state=self._last_state["flows"][name], state=self._state["flows"][name], ) if name in self._state.get("structures", {}): return AppState( self._host, self._port, last_state=self._last_state["structures"][name], state=self._state["structures"][name], ) raise AttributeError( f"Failed to access '{name}' through `AppState`. The state provides:" f" Variables: {list(self._state['vars'].keys())}," f" Components: {list(self._state.get('flows', {}).keys()) + list(self._state.get('works', {}).keys())}", ) def __getitem__(self, key: str): return self.__getattr__(key) def __setattr__(self, name: str, value: Any) -> None: if name in self._APP_PRIVATE_KEYS: object.__setattr__(self, name, value) return # The state needs to be fetched on access if it doesn't exist. self._request_state() # TODO: Find a way to aggregate deltas to avoid making # request for each attribute change. if name in self._state["vars"]: self._state["vars"][name] = value self.send_delta() elif name in self._state["flows"]: raise AttributeError("You shouldn't set the flows directly onto the state. Use its attributes instead.") elif name in self._state["works"]: raise AttributeError("You shouldn't set the works directly onto the state. Use its attributes instead.") else: raise AttributeError( f"Failed to access '{name}' through `AppState`. The state provides:" f" Variables: {list(self._state['vars'].keys())}," f" Components: {list(self._state['flows'].keys()) + list(self._state['works'].keys())}", ) def __repr__(self) -> str: return str(self._state) def __bool__(self) -> bool: return bool(self._state) def __len__(self) -> int: # The state needs to be fetched on access if it doesn't exist. self._request_state() keys = [] for component in ["flows", "works", "structures"]: keys.extend(list(self._state.get(component, {}))) return len(keys) def items(self) -> List[Dict[str, Any]]: # The state needs to be fetched on access if it doesn't exist. self._request_state() items = [] for component in ["flows", "works"]: state = self._state.get(component, {}) last_state = self._last_state.get(component, {}) for name, state_value in state.items(): v = AppState( self._host, self._port, last_state=last_state[name], state=state_value, ) items.append((name, v)) structures = self._state.get("structures", {}) last_structures = self._last_state.get("structures", {}) if structures: for component in ["flows", "works"]: state = structures.get(component, {}) last_state = last_structures.get(component, {}) for name, state_value in state.items(): v = AppState( self._host, self._port, last_state=last_state[name], state=state_value, ) items.append((name, v)) return items def _configure_session() -> Session: return _configure_session() def _main() -> None: # Get the AppState app_state = AppState(plugin=StreamLitStatePlugin()) work_state = _reduce_to_component_scope(app_state, os.environ["LIGHTNING_COMPONENT_NAME"]) # Create the patched work work_class = _get_work_class() patched_work = _PatchedWork(work_state, work_class) # Build and attach the model _build_model(patched_work) # Render patched_work.render()
null
155,695
import functools import json import pathlib from typing import Any, Dict, Generic, List, Type, TypeVar from fastapi import Response, status from fastapi.encoders import jsonable_encoder from lightning_utilities.core.imports import RequirementCache from pydantic import BaseModel, parse_obj_as from lightning.app.utilities.app_helpers import Logger from lightning.app.utilities.imports import _is_sqlmodel_available T = TypeVar("T") The provided code snippet includes necessary dependencies for implementing the `_pydantic_column_type` function. Write a Python function `def _pydantic_column_type(pydantic_type: Any) -> Any` to solve the following problem: This function enables to support JSON types with SQLModel. Example:: from sqlmodel import SQLModel from sqlalchemy import Column class TrialConfig(SQLModel, table=False): ... params: Dict[str, Union[Dict[str, float]] = Field(sa_column=Column(pydantic_column_type[Dict[str, float])) Here is the function: def _pydantic_column_type(pydantic_type: Any) -> Any: """This function enables to support JSON types with SQLModel. Example:: from sqlmodel import SQLModel from sqlalchemy import Column class TrialConfig(SQLModel, table=False): ... params: Dict[str, Union[Dict[str, float]] = Field(sa_column=Column(pydantic_column_type[Dict[str, float])) """ class PydanticJSONType(TypeDecorator, Generic[T]): impl = JSON() def __init__( self, json_encoder=json, ): self.json_encoder = json_encoder super().__init__() def bind_processor(self, dialect): impl_processor = self.impl.bind_processor(dialect) dumps = self.json_encoder.dumps if impl_processor: def process(value: T): if value is not None: if isinstance(pydantic_type, ModelMetaclass): # This allows to assign non-InDB models and if they're # compatible, they're directly parsed into the InDB # representation, thus hiding the implementation in the # background. However, the InDB model will still be returned value_to_dump = pydantic_type.from_orm(value) else: value_to_dump = value value = jsonable_encoder(value_to_dump) return impl_processor(value) else: def process(value): if isinstance(pydantic_type, ModelMetaclass): # This allows to assign non-InDB models and if they're # compatible, they're directly parsed into the InDB # representation, thus hiding the implementation in the # background. However, the InDB model will still be returned value_to_dump = pydantic_type.from_orm(value) else: value_to_dump = value return dumps(jsonable_encoder(value_to_dump)) return process def result_processor(self, dialect, coltype) -> T: impl_processor = self.impl.result_processor(dialect, coltype) if impl_processor: def process(value): value = impl_processor(value) if value is None: return None data = value # Explicitly use the generic directly, not type(T) return parse_obj_as(pydantic_type, data) else: def process(value): if value is None: return None # Explicitly use the generic directly, not type(T) return parse_obj_as(pydantic_type, value) return process def compare_values(self, x, y): return x == y return PydanticJSONType
This function enables to support JSON types with SQLModel. Example:: from sqlmodel import SQLModel from sqlalchemy import Column class TrialConfig(SQLModel, table=False): ... params: Dict[str, Union[Dict[str, float]] = Field(sa_column=Column(pydantic_column_type[Dict[str, float]))
155,696
import functools import json import pathlib from typing import Any, Dict, Generic, List, Type, TypeVar from fastapi import Response, status from fastapi.encoders import jsonable_encoder from lightning_utilities.core.imports import RequirementCache from pydantic import BaseModel, parse_obj_as from lightning.app.utilities.app_helpers import Logger from lightning.app.utilities.imports import _is_sqlmodel_available def _get_primary_key(model_type: Type["SQLModel"]) -> str: primary_keys = sqlalchemy_inspect(model_type).primary_key if len(primary_keys) != 1: raise ValueError(f"The model {model_type.__name__} should have a single primary key field.") return primary_keys[0].name
null
155,697
import functools import json import pathlib from typing import Any, Dict, Generic, List, Type, TypeVar from fastapi import Response, status from fastapi.encoders import jsonable_encoder from lightning_utilities.core.imports import RequirementCache from pydantic import BaseModel, parse_obj_as from lightning.app.utilities.app_helpers import Logger from lightning.app.utilities.imports import _is_sqlmodel_available logger = Logger(__name__) engine = None def _create_database(db_filename: str, models: List[Type["SQLModel"]], echo: bool = False): global engine from sqlmodel import create_engine engine = create_engine(f"sqlite:///{pathlib.Path(db_filename).resolve()}", echo=echo) logger.debug(f"Creating the following tables {models}") try: SQLModel.metadata.create_all(engine) except Exception as ex: logger.debug(ex)
null
155,698
from typing import Any, Dict, List, Optional, Type, TypeVar import requests from requests import Session from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from lightning.app.components.database.utilities import _GeneralModel _CONNECTION_RETRY_TOTAL = 5 _CONNECTION_RETRY_BACKOFF_FACTOR = 1 The provided code snippet includes necessary dependencies for implementing the `_configure_session` function. Write a Python function `def _configure_session() -> Session` to solve the following problem: Configures the session for GET and POST requests. It enables a generous retrial strategy that waits for the application server to connect. Here is the function: def _configure_session() -> Session: """Configures the session for GET and POST requests. It enables a generous retrial strategy that waits for the application server to connect. """ retry_strategy = Retry( # wait time between retries increases exponentially according to: backoff_factor * (2 ** (retry - 1)) total=_CONNECTION_RETRY_TOTAL, backoff_factor=_CONNECTION_RETRY_BACKOFF_FACTOR, status_forcelist=[429, 500, 502, 503, 504], ) adapter = HTTPAdapter(max_retries=retry_strategy) http = requests.Session() http.mount("https://", adapter) http.mount("http://", adapter) return http
Configures the session for GET and POST requests. It enables a generous retrial strategy that waits for the application server to connect.
155,699
import inspect import json import logging import os import random import string import urllib from time import monotonic, sleep, time from typing import List, Optional from lightning_cloud.openapi import ( AppinstancesIdBody, Externalv1LightningappInstance, Externalv1Lightningwork, V1BuildSpec, V1Drive, V1DriveSpec, V1DriveStatus, V1DriveType, V1Flowserver, V1LightningappInstanceState, V1LightningappRestartPolicy, V1LightningworkClusterDriver, V1LightningworkDrives, V1LightningworkSpec, V1LightningworkState, V1ListLightningworkResponse, V1Metadata, V1NetworkConfig, V1PackageManager, V1PythonDependencyInfo, V1SourceType, V1UserRequestedComputeConfig, ) from lightning_cloud.openapi.rest import ApiException from lightning.app.core import LightningApp, LightningWork from lightning.app.core.queues import QueuingSystem from lightning.app.runners.backends.backend import Backend from lightning.app.storage import Drive, Mount from lightning.app.utilities.enum import WorkStageStatus, WorkStopReasons, make_status from lightning.app.utilities.exceptions import LightningPlatformException from lightning.app.utilities.network import LightningClient, _check_service_url_is_ready from lightning_cloud.openapi import SpecLightningappInstanceIdWorksBody, WorksIdBody class WorkStageStatus: NOT_STARTED = "not_started" STARTED = "started" STOPPED = "stopped" PENDING = "pending" RUNNING = "running" SUCCEEDED = "succeeded" FAILED = "failed" The provided code snippet includes necessary dependencies for implementing the `cloud_work_stage_to_work_status_stage` function. Write a Python function `def cloud_work_stage_to_work_status_stage(stage: V1LightningworkState) -> str` to solve the following problem: Maps the Work stage names from the cloud backend to the status names in the Lightning framework. Here is the function: def cloud_work_stage_to_work_status_stage(stage: V1LightningworkState) -> str: """Maps the Work stage names from the cloud backend to the status names in the Lightning framework.""" mapping = { V1LightningworkState.STOPPED: WorkStageStatus.STOPPED, V1LightningworkState.PENDING: WorkStageStatus.PENDING, V1LightningworkState.NOT_STARTED: WorkStageStatus.PENDING, V1LightningworkState.IMAGE_BUILDING: WorkStageStatus.PENDING, V1LightningworkState.RUNNING: WorkStageStatus.RUNNING, V1LightningworkState.FAILED: WorkStageStatus.FAILED, } if stage not in mapping: raise ValueError(f"Cannot map the lightning-cloud work state {stage} to the lightning status stage.") return mapping[stage]
Maps the Work stage names from the cloud backend to the status names in the Lightning framework.
155,700
import inspect import json import logging import os import random import string import urllib from time import monotonic, sleep, time from typing import List, Optional from lightning_cloud.openapi import ( AppinstancesIdBody, Externalv1LightningappInstance, Externalv1Lightningwork, V1BuildSpec, V1Drive, V1DriveSpec, V1DriveStatus, V1DriveType, V1Flowserver, V1LightningappInstanceState, V1LightningappRestartPolicy, V1LightningworkClusterDriver, V1LightningworkDrives, V1LightningworkSpec, V1LightningworkState, V1ListLightningworkResponse, V1Metadata, V1NetworkConfig, V1PackageManager, V1PythonDependencyInfo, V1SourceType, V1UserRequestedComputeConfig, ) from lightning_cloud.openapi.rest import ApiException from lightning.app.core import LightningApp, LightningWork from lightning.app.core.queues import QueuingSystem from lightning.app.runners.backends.backend import Backend from lightning.app.storage import Drive, Mount from lightning.app.utilities.enum import WorkStageStatus, WorkStopReasons, make_status from lightning.app.utilities.exceptions import LightningPlatformException from lightning.app.utilities.network import LightningClient, _check_service_url_is_ready from lightning_cloud.openapi import SpecLightningappInstanceIdWorksBody, WorksIdBody def _create_mount_drive_spec(work_name: str, mount: "Mount") -> V1LightningworkDrives: if mount.protocol == "s3://": drive_type = V1DriveType.INDEXED_S3 source_type = V1SourceType.S3 else: raise RuntimeError( f"unknown mounts protocol `{mount.protocol}`. Please verify this " f"drive type has been configured for use in the cloud dispatcher." ) return V1LightningworkDrives( drive=V1Drive( metadata=V1Metadata( name=work_name, ), spec=V1DriveSpec( drive_type=drive_type, source_type=source_type, source=mount.source, ), status=V1DriveStatus(), ), mount_location=str(mount.mount_path), )
null
155,701
from __future__ import annotations import inspect import os from typing import Callable from lightning.app.core.flow import LightningFlow from lightning.app.utilities.state import AppState def _reduce_to_flow_scope(state: AppState, flow: str | LightningFlow) -> AppState: """Returns a new AppState with the scope reduced to the given flow.""" flow_name = flow.name if isinstance(flow, LightningFlow) else flow flow_name_parts = flow_name.split(".")[1:] # exclude root flow_state = state for part in flow_name_parts: flow_state = getattr(flow_state, part) return flow_state class AppState: _APP_PRIVATE_KEYS: Tuple[str, ...] = ( "_use_localhost", "_host", "_session_id", "_state", "_last_state", "_url", "_port", "_request_state", "_store_state", "_send_state", "_my_affiliation", "_find_state_under_affiliation", "_plugin", "_attach_plugin", "_authorized", "is_authorized", "_debug", "_session", ) _MY_AFFILIATION: Tuple[str, ...] = () def __init__( self, host: Optional[str] = None, port: Optional[int] = None, last_state: Optional[Dict] = None, state: Optional[Dict] = None, my_affiliation: Tuple[str, ...] = None, plugin: Optional[BaseStatePlugin] = None, ) -> None: """The AppState class enables Frontend users to interact with their application state. When the state isn't defined, it would be pulled from the app REST API Server. If the state gets modified by the user, the new state would be sent to the API Server. Arguments: host: Rest API Server current host port: Rest API Server current port last_state: The state pulled on first access. state: The state modified by the user. my_affiliation: A tuple describing the affiliation this app state represents. When storing a state dict on this AppState, this affiliation will be used to reduce the scope of the given state. plugin: A plugin to handle authorization. """ self._use_localhost = "LIGHTNING_APP_STATE_URL" not in os.environ self._host = host or ("http://127.0.0.1" if self._use_localhost else None) self._port = port or (APP_SERVER_PORT if self._use_localhost else None) self._last_state = last_state self._state = state self._session_id = "1234" self._my_affiliation = my_affiliation if my_affiliation is not None else AppState._MY_AFFILIATION self._authorized = None self._attach_plugin(plugin) self._session = self._configure_session() def _url(self) -> str: if self._host is None: app_ip = "" if "LIGHTNING_CLOUD_PROJECT_ID" in os.environ and "LIGHTNING_CLOUD_APP_ID" in os.environ: client = LightningClient() app_instance = client.lightningapp_instance_service_get_lightningapp_instance( os.environ.get("LIGHTNING_CLOUD_PROJECT_ID"), os.environ.get("LIGHTNING_CLOUD_APP_ID"), ) app_ip = app_instance.status.ip_address # TODO: Don't hard code port 8080 here self._host = f"http://{app_ip}:8080" if app_ip else APP_SERVER_HOST return f"{self._host}:{self._port}" if self._use_localhost else self._host def _attach_plugin(self, plugin: Optional[BaseStatePlugin]) -> None: plugin = plugin if plugin is not None else AppStatePlugin() self._plugin = plugin def _find_state_under_affiliation(state, my_affiliation: Tuple[str, ...]) -> Dict[str, Any]: """This method is used to extract the subset of the app state associated with the given affiliation. For example, if the affiliation is ``("root", "subflow")``, then the returned state will be ``state["flows"]["subflow"]``. """ children_state = state for name in my_affiliation: if name in children_state["flows"]: children_state = children_state["flows"][name] elif name in children_state["works"]: children_state = children_state["works"][name] else: raise ValueError(f"Failed to extract the state under the affiliation '{my_affiliation}'.") return children_state def _store_state(self, state: Dict[str, Any]) -> None: # Relying on the global variable to ensure the # deep_diff is done on the entire state. global _LAST_STATE global _STATE _LAST_STATE = deepcopy(state) _STATE = state # If the affiliation is passed, the AppState was created in a LightningFlow context. # The state should be only the one of this LightningFlow and its children. self._last_state = self._find_state_under_affiliation(_LAST_STATE, self._my_affiliation) self._state = self._find_state_under_affiliation(_STATE, self._my_affiliation) def send_delta(self) -> None: app_url = f"{self._url}/api/v1/delta" deep_diff = DeepDiff(_LAST_STATE, _STATE, verbose_level=2) assert self._plugin is not None # TODO: Find how to prevent the infinite loop on refresh without storing the DeepDiff if self._plugin.should_update_app(deep_diff): data = {"delta": json.loads(deep_diff.to_json())} headers = headers_for(self._plugin.get_context()) try: # TODO: Send the delta directly to the REST API. response = self._session.post(app_url, json=data, headers=headers) except ConnectionError as ex: raise AttributeError("Failed to connect and send the app state. Is the app running?") from ex if response and response.status_code != 200: raise Exception(f"The response from the server was {response.status_code}. Your inputs were rejected.") def _request_state(self) -> None: if self._state is not None: return app_url = f"{self._url}/api/v1/state" headers = headers_for(self._plugin.get_context()) if self._plugin else {} response_json = {} # Sometimes the state URL can return an empty JSON when things are being set-up, # so we wait for it to be ready here. while response_json == {}: sleep(0.5) try: response = self._session.get(app_url, headers=headers, timeout=1) except ConnectionError as ex: raise AttributeError("Failed to connect and fetch the app state. Is the app running?") from ex self._authorized = response.status_code if self._authorized != 200: return response_json = response.json() logger.debug(f"GET STATE {response} {response_json}") self._store_state(response_json) def __getattr__(self, name: str) -> Union[Any, "AppState"]: if name in self._APP_PRIVATE_KEYS: return object.__getattr__(self, name) # The state needs to be fetched on access if it doesn't exist. self._request_state() if name in self._state.get("vars", {}): value = self._state["vars"][name] if isinstance(value, dict): return _maybe_create_drive("root." + ".".join(self._my_affiliation), value) return value if name in self._state.get("works", {}): return AppState( self._host, self._port, last_state=self._last_state["works"][name], state=self._state["works"][name] ) if name in self._state.get("flows", {}): return AppState( self._host, self._port, last_state=self._last_state["flows"][name], state=self._state["flows"][name], ) if name in self._state.get("structures", {}): return AppState( self._host, self._port, last_state=self._last_state["structures"][name], state=self._state["structures"][name], ) raise AttributeError( f"Failed to access '{name}' through `AppState`. The state provides:" f" Variables: {list(self._state['vars'].keys())}," f" Components: {list(self._state.get('flows', {}).keys()) + list(self._state.get('works', {}).keys())}", ) def __getitem__(self, key: str): return self.__getattr__(key) def __setattr__(self, name: str, value: Any) -> None: if name in self._APP_PRIVATE_KEYS: object.__setattr__(self, name, value) return # The state needs to be fetched on access if it doesn't exist. self._request_state() # TODO: Find a way to aggregate deltas to avoid making # request for each attribute change. if name in self._state["vars"]: self._state["vars"][name] = value self.send_delta() elif name in self._state["flows"]: raise AttributeError("You shouldn't set the flows directly onto the state. Use its attributes instead.") elif name in self._state["works"]: raise AttributeError("You shouldn't set the works directly onto the state. Use its attributes instead.") else: raise AttributeError( f"Failed to access '{name}' through `AppState`. The state provides:" f" Variables: {list(self._state['vars'].keys())}," f" Components: {list(self._state['flows'].keys()) + list(self._state['works'].keys())}", ) def __repr__(self) -> str: return str(self._state) def __bool__(self) -> bool: return bool(self._state) def __len__(self) -> int: # The state needs to be fetched on access if it doesn't exist. self._request_state() keys = [] for component in ["flows", "works", "structures"]: keys.extend(list(self._state.get(component, {}))) return len(keys) def items(self) -> List[Dict[str, Any]]: # The state needs to be fetched on access if it doesn't exist. self._request_state() items = [] for component in ["flows", "works"]: state = self._state.get(component, {}) last_state = self._last_state.get(component, {}) for name, state_value in state.items(): v = AppState( self._host, self._port, last_state=last_state[name], state=state_value, ) items.append((name, v)) structures = self._state.get("structures", {}) last_structures = self._last_state.get("structures", {}) if structures: for component in ["flows", "works"]: state = structures.get(component, {}) last_state = last_structures.get(component, {}) for name, state_value in state.items(): v = AppState( self._host, self._port, last_state=last_state[name], state=state_value, ) items.append((name, v)) return items def _configure_session() -> Session: return _configure_session() The provided code snippet includes necessary dependencies for implementing the `_get_flow_state` function. Write a Python function `def _get_flow_state(flow: str) -> AppState` to solve the following problem: Returns an AppState scoped to the current Flow. Returns: AppState: An AppState scoped to the current Flow. Here is the function: def _get_flow_state(flow: str) -> AppState: """Returns an AppState scoped to the current Flow. Returns: AppState: An AppState scoped to the current Flow. """ app_state = AppState() app_state._request_state() # pylint: disable=protected-access return _reduce_to_flow_scope(app_state, flow)
Returns an AppState scoped to the current Flow. Returns: AppState: An AppState scoped to the current Flow.
155,702
from __future__ import annotations import inspect import os from typing import Callable from lightning.app.core.flow import LightningFlow from lightning.app.utilities.state import AppState The provided code snippet includes necessary dependencies for implementing the `_get_frontend_environment` function. Write a Python function `def _get_frontend_environment(flow: str, render_fn_or_file: Callable | str, port: int, host: str) -> os._Environ` to solve the following problem: Returns an _Environ with the environment variables for serving a Frontend app set. Args: flow: The name of the flow, for example root.lit_frontend render_fn_or_file: A function to render port: The port number, for example 54321 host: The host, for example 'localhost' Returns: os._Environ: An environment Here is the function: def _get_frontend_environment(flow: str, render_fn_or_file: Callable | str, port: int, host: str) -> os._Environ: """Returns an _Environ with the environment variables for serving a Frontend app set. Args: flow: The name of the flow, for example root.lit_frontend render_fn_or_file: A function to render port: The port number, for example 54321 host: The host, for example 'localhost' Returns: os._Environ: An environment """ env = os.environ.copy() env["LIGHTNING_FLOW_NAME"] = flow env["LIGHTNING_RENDER_PORT"] = str(port) env["LIGHTNING_RENDER_ADDRESS"] = str(host) if isinstance(render_fn_or_file, str): env["LIGHTNING_RENDER_FILE"] = render_fn_or_file else: env["LIGHTNING_RENDER_FUNCTION"] = render_fn_or_file.__name__ env["LIGHTNING_RENDER_MODULE_FILE"] = inspect.getmodule(render_fn_or_file).__file__ return env
Returns an _Environ with the environment variables for serving a Frontend app set. Args: flow: The name of the flow, for example root.lit_frontend render_fn_or_file: A function to render port: The port number, for example 54321 host: The host, for example 'localhost' Returns: os._Environ: An environment
155,703
import os import pydoc from typing import Callable from lightning.app.frontend.utils import _reduce_to_flow_scope from lightning.app.utilities.app_helpers import StreamLitStatePlugin from lightning.app.utilities.state import AppState def _get_render_fn_from_environment() -> Callable: render_fn_name = os.environ["LIGHTNING_RENDER_FUNCTION"] render_fn_module_file = os.environ["LIGHTNING_RENDER_MODULE_FILE"] module = pydoc.importfile(render_fn_module_file) return getattr(module, render_fn_name) def _reduce_to_flow_scope(state: AppState, flow: str | LightningFlow) -> AppState: """Returns a new AppState with the scope reduced to the given flow.""" flow_name = flow.name if isinstance(flow, LightningFlow) else flow flow_name_parts = flow_name.split(".")[1:] # exclude root flow_state = state for part in flow_name_parts: flow_state = getattr(flow_state, part) return flow_state class StreamLitStatePlugin(BaseStatePlugin): def __init__(self): super().__init__() import streamlit as st if hasattr(st, "session_state") and "websocket_thread" not in st.session_state: thread = threading.Thread(target=target_fn) st.session_state.websocket_thread = thread thread.setDaemon(True) thread.start() def should_update_app(self, deep_diff): return deep_diff def get_context(self): return {"type": AppStateType.DEFAULT.value} def render_non_authorized(self): pass class AppState: _APP_PRIVATE_KEYS: Tuple[str, ...] = ( "_use_localhost", "_host", "_session_id", "_state", "_last_state", "_url", "_port", "_request_state", "_store_state", "_send_state", "_my_affiliation", "_find_state_under_affiliation", "_plugin", "_attach_plugin", "_authorized", "is_authorized", "_debug", "_session", ) _MY_AFFILIATION: Tuple[str, ...] = () def __init__( self, host: Optional[str] = None, port: Optional[int] = None, last_state: Optional[Dict] = None, state: Optional[Dict] = None, my_affiliation: Tuple[str, ...] = None, plugin: Optional[BaseStatePlugin] = None, ) -> None: """The AppState class enables Frontend users to interact with their application state. When the state isn't defined, it would be pulled from the app REST API Server. If the state gets modified by the user, the new state would be sent to the API Server. Arguments: host: Rest API Server current host port: Rest API Server current port last_state: The state pulled on first access. state: The state modified by the user. my_affiliation: A tuple describing the affiliation this app state represents. When storing a state dict on this AppState, this affiliation will be used to reduce the scope of the given state. plugin: A plugin to handle authorization. """ self._use_localhost = "LIGHTNING_APP_STATE_URL" not in os.environ self._host = host or ("http://127.0.0.1" if self._use_localhost else None) self._port = port or (APP_SERVER_PORT if self._use_localhost else None) self._last_state = last_state self._state = state self._session_id = "1234" self._my_affiliation = my_affiliation if my_affiliation is not None else AppState._MY_AFFILIATION self._authorized = None self._attach_plugin(plugin) self._session = self._configure_session() def _url(self) -> str: if self._host is None: app_ip = "" if "LIGHTNING_CLOUD_PROJECT_ID" in os.environ and "LIGHTNING_CLOUD_APP_ID" in os.environ: client = LightningClient() app_instance = client.lightningapp_instance_service_get_lightningapp_instance( os.environ.get("LIGHTNING_CLOUD_PROJECT_ID"), os.environ.get("LIGHTNING_CLOUD_APP_ID"), ) app_ip = app_instance.status.ip_address # TODO: Don't hard code port 8080 here self._host = f"http://{app_ip}:8080" if app_ip else APP_SERVER_HOST return f"{self._host}:{self._port}" if self._use_localhost else self._host def _attach_plugin(self, plugin: Optional[BaseStatePlugin]) -> None: plugin = plugin if plugin is not None else AppStatePlugin() self._plugin = plugin def _find_state_under_affiliation(state, my_affiliation: Tuple[str, ...]) -> Dict[str, Any]: """This method is used to extract the subset of the app state associated with the given affiliation. For example, if the affiliation is ``("root", "subflow")``, then the returned state will be ``state["flows"]["subflow"]``. """ children_state = state for name in my_affiliation: if name in children_state["flows"]: children_state = children_state["flows"][name] elif name in children_state["works"]: children_state = children_state["works"][name] else: raise ValueError(f"Failed to extract the state under the affiliation '{my_affiliation}'.") return children_state def _store_state(self, state: Dict[str, Any]) -> None: # Relying on the global variable to ensure the # deep_diff is done on the entire state. global _LAST_STATE global _STATE _LAST_STATE = deepcopy(state) _STATE = state # If the affiliation is passed, the AppState was created in a LightningFlow context. # The state should be only the one of this LightningFlow and its children. self._last_state = self._find_state_under_affiliation(_LAST_STATE, self._my_affiliation) self._state = self._find_state_under_affiliation(_STATE, self._my_affiliation) def send_delta(self) -> None: app_url = f"{self._url}/api/v1/delta" deep_diff = DeepDiff(_LAST_STATE, _STATE, verbose_level=2) assert self._plugin is not None # TODO: Find how to prevent the infinite loop on refresh without storing the DeepDiff if self._plugin.should_update_app(deep_diff): data = {"delta": json.loads(deep_diff.to_json())} headers = headers_for(self._plugin.get_context()) try: # TODO: Send the delta directly to the REST API. response = self._session.post(app_url, json=data, headers=headers) except ConnectionError as ex: raise AttributeError("Failed to connect and send the app state. Is the app running?") from ex if response and response.status_code != 200: raise Exception(f"The response from the server was {response.status_code}. Your inputs were rejected.") def _request_state(self) -> None: if self._state is not None: return app_url = f"{self._url}/api/v1/state" headers = headers_for(self._plugin.get_context()) if self._plugin else {} response_json = {} # Sometimes the state URL can return an empty JSON when things are being set-up, # so we wait for it to be ready here. while response_json == {}: sleep(0.5) try: response = self._session.get(app_url, headers=headers, timeout=1) except ConnectionError as ex: raise AttributeError("Failed to connect and fetch the app state. Is the app running?") from ex self._authorized = response.status_code if self._authorized != 200: return response_json = response.json() logger.debug(f"GET STATE {response} {response_json}") self._store_state(response_json) def __getattr__(self, name: str) -> Union[Any, "AppState"]: if name in self._APP_PRIVATE_KEYS: return object.__getattr__(self, name) # The state needs to be fetched on access if it doesn't exist. self._request_state() if name in self._state.get("vars", {}): value = self._state["vars"][name] if isinstance(value, dict): return _maybe_create_drive("root." + ".".join(self._my_affiliation), value) return value if name in self._state.get("works", {}): return AppState( self._host, self._port, last_state=self._last_state["works"][name], state=self._state["works"][name] ) if name in self._state.get("flows", {}): return AppState( self._host, self._port, last_state=self._last_state["flows"][name], state=self._state["flows"][name], ) if name in self._state.get("structures", {}): return AppState( self._host, self._port, last_state=self._last_state["structures"][name], state=self._state["structures"][name], ) raise AttributeError( f"Failed to access '{name}' through `AppState`. The state provides:" f" Variables: {list(self._state['vars'].keys())}," f" Components: {list(self._state.get('flows', {}).keys()) + list(self._state.get('works', {}).keys())}", ) def __getitem__(self, key: str): return self.__getattr__(key) def __setattr__(self, name: str, value: Any) -> None: if name in self._APP_PRIVATE_KEYS: object.__setattr__(self, name, value) return # The state needs to be fetched on access if it doesn't exist. self._request_state() # TODO: Find a way to aggregate deltas to avoid making # request for each attribute change. if name in self._state["vars"]: self._state["vars"][name] = value self.send_delta() elif name in self._state["flows"]: raise AttributeError("You shouldn't set the flows directly onto the state. Use its attributes instead.") elif name in self._state["works"]: raise AttributeError("You shouldn't set the works directly onto the state. Use its attributes instead.") else: raise AttributeError( f"Failed to access '{name}' through `AppState`. The state provides:" f" Variables: {list(self._state['vars'].keys())}," f" Components: {list(self._state['flows'].keys()) + list(self._state['works'].keys())}", ) def __repr__(self) -> str: return str(self._state) def __bool__(self) -> bool: return bool(self._state) def __len__(self) -> int: # The state needs to be fetched on access if it doesn't exist. self._request_state() keys = [] for component in ["flows", "works", "structures"]: keys.extend(list(self._state.get(component, {}))) return len(keys) def items(self) -> List[Dict[str, Any]]: # The state needs to be fetched on access if it doesn't exist. self._request_state() items = [] for component in ["flows", "works"]: state = self._state.get(component, {}) last_state = self._last_state.get(component, {}) for name, state_value in state.items(): v = AppState( self._host, self._port, last_state=last_state[name], state=state_value, ) items.append((name, v)) structures = self._state.get("structures", {}) last_structures = self._last_state.get("structures", {}) if structures: for component in ["flows", "works"]: state = structures.get(component, {}) last_state = last_structures.get(component, {}) for name, state_value in state.items(): v = AppState( self._host, self._port, last_state=last_state[name], state=state_value, ) items.append((name, v)) return items def _configure_session() -> Session: return _configure_session() The provided code snippet includes necessary dependencies for implementing the `_main` function. Write a Python function `def _main()` to solve the following problem: Run the render_fn with the current flow_state. Here is the function: def _main(): """Run the render_fn with the current flow_state.""" app_state = AppState(plugin=StreamLitStatePlugin()) # Fetch the information of which flow attaches to this streamlit instance flow_state = _reduce_to_flow_scope(app_state, flow=os.environ["LIGHTNING_FLOW_NAME"]) # Call the provided render function. # Pass it the state, scoped to the current flow. render_fn = _get_render_fn_from_environment() render_fn(flow_state)
Run the render_fn with the current flow_state.
155,704
import os import pydoc from typing import Any, Callable from lightning.app.frontend.utils import _reduce_to_flow_scope from lightning.app.utilities.state import AppState def _get_state() -> AppState: app_state = AppState() return _reduce_to_flow_scope(app_state, flow=os.environ["LIGHTNING_FLOW_NAME"]) def _webpage() -> Any: import justpy as jp wp = jp.WebPage() d = jp.Div(text="") wp.add(d) return wp def _get_render_fn_from_environment() -> Callable: render_fn_name = os.environ["LIGHTNING_RENDER_FUNCTION"] render_fn_module_file = os.environ["LIGHTNING_RENDER_MODULE_FILE"] module = pydoc.importfile(render_fn_module_file) return getattr(module, render_fn_name) The provided code snippet includes necessary dependencies for implementing the `_main` function. Write a Python function `def _main() -> None` to solve the following problem: Run the render_fn with the current flow_state. Here is the function: def _main() -> None: """Run the render_fn with the current flow_state.""" import justpy as jp # Fetch the information of which flow attaches to this justpy instance flow_name = os.environ["LIGHTNING_FLOW_NAME"] # Call the provided render function. # Pass it the state, scoped to the current flow. render_fn = _get_render_fn_from_environment() host = os.environ["LIGHTNING_HOST"] port = int(os.environ["LIGHTNING_PORT"]) entry_fn = render_fn(_get_state) if not isinstance(entry_fn, Callable): # type: ignore raise Exception("You need to return a function with JustPy Frontend.") jp.app.add_jproute(f"/{flow_name}", entry_fn) jp.justpy(_webpage, host=host, port=port)
Run the render_fn with the current flow_state.
155,705
import multiprocessing as mp from argparse import ArgumentParser from typing import Optional from urllib.parse import urljoin import uvicorn from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from starlette.staticfiles import StaticFiles from lightning.app.frontend.frontend import Frontend from lightning.app.utilities.log import get_logfile from lightning.app.utilities.network import find_free_network_port def _healthz(): """Health check endpoint used in the cloud FastAPI servers to check the status periodically.""" return {"status": "ok"} def _get_log_config(log_file: str) -> dict: """Returns a logger configuration in the format expected by uvicorn that sends all logs to the given logfile.""" # Modified from the default config found in uvicorn.config.LOGGING_CONFIG return { "version": 1, "disable_existing_loggers": False, "formatters": { "default": { "()": "uvicorn.logging.DefaultFormatter", "fmt": "%(levelprefix)s %(message)s", "use_colors": False, }, }, "handlers": { "default": { "formatter": "default", "class": "logging.FileHandler", "filename": log_file, }, }, "loggers": { "uvicorn": {"handlers": ["default"], "level": "INFO", "propagate": False}, "uvicorn.error": {"handlers": ["default"], "level": "INFO", "propagate": False}, "uvicorn.access": {"handlers": ["default"], "level": "INFO", "propagate": False}, }, } def find_free_network_port() -> int: """Finds a free port on localhost.""" if constants.LIGHTNING_CLOUDSPACE_HOST is not None: return _find_free_network_port_cloudspace() port = None for _ in range(10): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("", 0)) port = sock.getsockname()[1] sock.close() if port not in _reserved_ports: break if port in _reserved_ports: # Prevent an infinite loop, if we tried 10 times and didn't get a free port then something is wrong raise RuntimeError( "Couldn't find a free port. Please open an issue at `https://github.com/Lightning-AI/lightning/issues`." ) _reserved_ports.add(port) return port def _start_server( serve_dir: str, host: str = "localhost", port: int = -1, path: str = "/", log_file: str = "", root_path: str = "" ) -> None: if port == -1: port = find_free_network_port() fastapi_service = FastAPI() fastapi_service.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # trailing / is required for urljoin to properly join the path. In case of # multiple trailing /, urljoin removes them fastapi_service.get(urljoin(f"{path}/", "healthz"), status_code=200)(_healthz) fastapi_service.mount(urljoin(path, root_path), StaticFiles(directory=serve_dir, html=True), name="static") log_config = _get_log_config(log_file) if log_file else uvicorn.config.LOGGING_CONFIG uvicorn.run(app=fastapi_service, host=host, port=port, log_config=log_config, root_path=root_path)
null
155,706
from __future__ import annotations import asyncio import os from threading import Thread from typing import Callable import websockets from lightning.app.core.constants import APP_SERVER_PORT from lightning.app.utilities.app_helpers import Logger _CALLBACKS = [] def _start_websocket(): global _THREAD # pylint: disable=global-statement if not _THREAD: _logger.debug("Starting the watch_app_state thread.") _THREAD = Thread(target=_target_fn) _THREAD.setDaemon(True) _THREAD.start() _logger.debug("thread started") The provided code snippet includes necessary dependencies for implementing the `_watch_app_state` function. Write a Python function `def _watch_app_state(callback: Callable)` to solve the following problem: Start the process that serves the UI at the given hostname and port number. Arguments: callback: A function to run when the App state changes. Must be thread safe. Example: .. code-block:: python def handle_state_change(): print("The App State changed.") watch_app_state(handle_state_change) Here is the function: def _watch_app_state(callback: Callable): """Start the process that serves the UI at the given hostname and port number. Arguments: callback: A function to run when the App state changes. Must be thread safe. Example: .. code-block:: python def handle_state_change(): print("The App State changed.") watch_app_state(handle_state_change) """ _CALLBACKS.append(callback) _start_websocket()
Start the process that serves the UI at the given hostname and port number. Arguments: callback: A function to run when the App state changes. Must be thread safe. Example: .. code-block:: python def handle_state_change(): print("The App State changed.") watch_app_state(handle_state_change)
155,707
import inspect import os import pydoc from typing import Callable from lightning.app.frontend.panel.app_state_watcher import AppStateWatcher def _get_render_fn(): render_fn_name = os.environ["LIGHTNING_RENDER_FUNCTION"] render_fn_module_file = os.environ["LIGHTNING_RENDER_MODULE_FILE"] render_fn = _get_render_fn_from_environment(render_fn_name, render_fn_module_file) if inspect.signature(render_fn).parameters: def _render_fn_wrapper(): app = AppStateWatcher() return render_fn(app) return _render_fn_wrapper return render_fn def _main(): import panel as pn # I use caching for efficiency reasons. It shaves off 10ms from having # to get_render_fn_from_environment every time if "lightning_render_fn" not in pn.state.cache: pn.state.cache["lightning_render_fn"] = _get_render_fn() pn.state.cache["lightning_render_fn"]()
null
155,708
from __future__ import annotations import inspect import os import pathlib import subprocess import sys from typing import Callable, TextIO from lightning.app.frontend.frontend import Frontend from lightning.app.frontend.utils import _get_frontend_environment from lightning.app.utilities.app_helpers import Logger from lightning.app.utilities.cloud import is_running_in_cloud from lightning.app.utilities.imports import requires from lightning.app.utilities.log import get_logfile The provided code snippet includes necessary dependencies for implementing the `_has_panel_autoreload` function. Write a Python function `def _has_panel_autoreload() -> bool` to solve the following problem: Returns True if the PANEL_AUTORELOAD environment variable is set to 'yes' or 'true'. Please note the casing of value does not matter Here is the function: def _has_panel_autoreload() -> bool: """Returns True if the PANEL_AUTORELOAD environment variable is set to 'yes' or 'true'. Please note the casing of value does not matter """ return os.environ.get("PANEL_AUTORELOAD", "no").lower() in ["yes", "y", "true"]
Returns True if the PANEL_AUTORELOAD environment variable is set to 'yes' or 'true'. Please note the casing of value does not matter
155,709
from __future__ import annotations import inspect import os import pathlib import subprocess import sys from typing import Callable, TextIO from lightning.app.frontend.frontend import Frontend from lightning.app.frontend.utils import _get_frontend_environment from lightning.app.utilities.app_helpers import Logger from lightning.app.utilities.cloud import is_running_in_cloud from lightning.app.utilities.imports import requires from lightning.app.utilities.log import get_logfile The provided code snippet includes necessary dependencies for implementing the `_get_allowed_hosts` function. Write a Python function `def _get_allowed_hosts() -> str` to solve the following problem: Returns a comma separated list of host[:port] that should be allowed to connect. Here is the function: def _get_allowed_hosts() -> str: """Returns a comma separated list of host[:port] that should be allowed to connect.""" # TODO: Enable only lightning.ai domain in the cloud return "*"
Returns a comma separated list of host[:port] that should be allowed to connect.
155,710
import multiprocessing import os import pdb import sys class MPPdb(pdb.Pdb): """A Pdb wrapper that works in a multiprocessing environment.""" def __init__(self) -> None: pdb.Pdb.__init__(self, nosigint=True) def _cmdloop(self) -> None: stdin_back = sys.stdin with _stdin_lock: try: if _stdin_fd is not None: if not _stdin[0]: _stdin[0] = os.fdopen(_stdin_fd) sys.stdin = _stdin[0] self.cmdloop() finally: sys.stdin = stdin_back import pdb def set_trace() -> None: pdb = MPPdb() pdb.set_trace(sys._getframe().f_back)
null
155,711
import os import pathlib import shutil import sys from copy import deepcopy from time import sleep, time from typing import Dict, List, Optional, Union from lightning.app.storage.path import LocalFileSystem, _filesystem, _shared_storage_path from lightning.app.utilities.component import _is_flow_context class Drive: __IDENTIFIER__ = "__drive__" __PROTOCOLS__ = ["lit://"] def __init__( self, id: str, allow_duplicates: bool = False, component_name: Optional[str] = None, root_folder: Optional[str] = None, ): """The Drive object provides a shared space to write and read files from. When the drive object is passed from one component to another, a copy is made and ownership is transferred to the new component. Arguments: id: Unique identifier for this Drive. allow_duplicates: Whether to enable files duplication between components. component_name: The component name which owns this drive. When not provided, it is automatically inferred by Lightning. root_folder: This is the folder from where the Drive perceives the data (e.g this acts as a mount dir). """ if id.startswith("s3://"): raise ValueError( "Using S3 buckets in a Drive is no longer supported. Please pass an S3 `Mount` to " "a Work's CloudCompute config in order to mount an s3 bucket as a filesystem in a work.\n" f"`CloudCompute(mount=Mount({id}), ...)`" ) self.id = None self.protocol = None for protocol in self.__PROTOCOLS__: if id.startswith(protocol): self.protocol = protocol self.id = id.replace(protocol, "") break else: # N.B. for-else loop raise ValueError( f"Unknown protocol for the drive 'id' argument '{id}`. The 'id' string " f"must start with one of the following prefixes {self.__PROTOCOLS__}" ) if not self.id: raise Exception(f"The Drive id needs to start with one of the following protocols: {self.__PROTOCOLS__}") if "/" in self.id: raise Exception(f"The id should be unique to identify your drive. Found `{self.id}`.") self.root_folder = pathlib.Path(root_folder).resolve() if root_folder else pathlib.Path(os.getcwd()) if self.protocol != "s3://" and not os.path.isdir(self.root_folder): raise Exception(f"The provided root_folder isn't a directory: {root_folder}") self.component_name = component_name self.allow_duplicates = allow_duplicates self.fs = _filesystem() def root(self) -> pathlib.Path: root_path = self.drive_root / self.component_name if isinstance(self.fs, LocalFileSystem): self.fs.makedirs(root_path, exist_ok=True) return root_path def drive_root(self) -> pathlib.Path: return _shared_storage_path() / "artifacts" / "drive" / self.id def put(self, path: str) -> None: """This method enables to put a file to the Drive in a blocking fashion. Arguments: path: The relative path to your files to be added to the Drive. """ if not self.component_name: raise Exception("The component name needs to be known to put a path to the Drive.") if _is_flow_context(): raise Exception("The flow isn't allowed to put files into a Drive.") self._validate_path(path) if not self.allow_duplicates: self._check_for_allow_duplicates(path) from lightning.app.storage.copier import _copy_files src = pathlib.Path(os.path.join(self.root_folder, path)).resolve() dst = self._to_shared_path(path, component_name=self.component_name) _copy_files(src, dst) def list(self, path: Optional[str] = ".", component_name: Optional[str] = None) -> List[str]: """This method enables to list files under the provided path from the Drive in a blocking fashion. Arguments: path: The relative path you want to list files from the Drive. component_name: By default, the Drive lists files across all components. If you provide a component name, the listing is specific to this component. """ if _is_flow_context(): raise Exception("The flow isn't allowed to list files from a Drive.") if component_name: paths = [ self._to_shared_path( path, component_name=component_name, ) ] else: paths = [ self._to_shared_path( path, component_name=component_name, ) for component_name in self._collect_component_names() ] files = [] sep = "\\" if sys.platform == "win32" else "/" prefix_len = len(str(self.root).split(sep)) for p in paths: if self.fs.exists(p): for f in self.fs.ls(p): files.append(str(pathlib.Path(*pathlib.Path(f).parts[prefix_len:]))) return files def get( self, path: str, component_name: Optional[str] = None, timeout: Optional[float] = None, overwrite: bool = False, ) -> None: """This method enables to get files under the provided path from the Drive in a blocking fashion. Arguments: path: The relative path you want to list files from the Drive. component_name: By default, the Drive get the matching files across all components. If you provide a component name, the matching is specific to this component. timeout: Whether to wait for the files to be available if not created yet. overwrite: Whether to override the provided path if it exists. """ if _is_flow_context(): raise Exception("The flow isn't allowed to get files from a Drive.") if component_name: shared_path = self._to_shared_path( path, component_name=component_name, ) if timeout: start_time = time() while not self.fs.exists(shared_path): sleep(1) if (time() - start_time) > timeout: raise Exception(f"The following {path} wasn't found in {timeout} seconds") break self._get( self.fs, shared_path, pathlib.Path(os.path.join(self.root_folder, path)).resolve(), overwrite=overwrite, ) else: if timeout: start_time = time() while True: if (time() - start_time) > timeout: raise Exception(f"The following {path} wasn't found in {timeout} seconds.") match = self._find_match(path) if match is None: sleep(1) continue break else: match = self._find_match(path) if not match: raise Exception(f"We didn't find any match for the associated {path}.") self._get(self.fs, match, pathlib.Path(os.path.join(self.root_folder, path)).resolve(), overwrite=overwrite) def delete(self, path: str) -> None: """This method enables to delete files under the provided path from the Drive in a blocking fashion. Only the component which added a file can delete them. Arguments: path: The relative path you want to delete files from the Drive. """ if not self.component_name: raise Exception("The component name needs to be known to delete a path to the Drive.") shared_path = self._to_shared_path( path, component_name=self.component_name, ) if self.fs.exists(str(shared_path)): self.fs.rm(str(shared_path)) else: raise Exception(f"The file {path} doesn't exists in the component_name space {self.component_name}.") def to_dict(self): return { "type": self.__IDENTIFIER__, "id": self.id, "protocol": self.protocol, "allow_duplicates": self.allow_duplicates, "component_name": self.component_name, "root_folder": str(self.root_folder), } def from_dict(cls, dict: Dict) -> "Drive": assert dict["type"] == cls.__IDENTIFIER__ drive = cls( dict["protocol"] + dict["id"], allow_duplicates=dict["allow_duplicates"], root_folder=dict["root_folder"], ) drive.component_name = dict["component_name"] return drive def __deepcopy__(self, memo): cls = self.__class__ result = cls.__new__(cls) memo[id(self)] = result for k, v in self.__dict__.items(): setattr(result, k, deepcopy(v, memo)) return result def _collect_component_names(self) -> List[str]: sep = "/" if self.fs.exists(self.drive_root): # Invalidate cache before running ls in case new directories have been added # TODO: Re-evaluate this - may lead to performance issues self.fs.invalidate_cache() return [str(p.split(sep)[-1]) for p in self.fs.ls(self.drive_root)] return [] def _to_shared_path(self, path: str, component_name: Optional[str] = None) -> pathlib.Path: shared_path = self.drive_root if component_name: shared_path /= component_name shared_path /= path return shared_path def _get(self, fs, src: pathlib.Path, dst: pathlib.Path, overwrite: bool): if fs.isdir(src): if isinstance(fs, LocalFileSystem): dst = dst.resolve() if fs.exists(dst): if overwrite: fs.rm(str(dst), recursive=True) else: raise FileExistsError(f"The file {dst} was found. Add get(..., overwrite=True) to replace it.") shutil.copytree(src, dst) else: glob = f"{str(src)}/**" fs.get(glob, str(dst.absolute()), recursive=False) else: fs.get(str(src), str(dst.absolute()), recursive=False) def _find_match(self, path: str) -> Optional[pathlib.Path]: matches = [] for component_name in self._collect_component_names(): possible_path = self._to_shared_path(path, component_name=component_name) if self.fs.exists(possible_path): matches.append(possible_path) if not matches: return None if len(matches) > 1: sep = "\\" if sys.platform == "win32" else "/" prefix_len = len(str(self.root).split(sep)) matches = [str(pathlib.Path(*pathlib.Path(p).parts[prefix_len:])) for p in matches] raise Exception(f"We found several matching files created by multiples components: {matches}.") return matches[0] def _check_for_allow_duplicates(self, path): possible_paths = [ self._to_shared_path( path, component_name=component_name, ) for component_name in self._collect_component_names() if component_name != self.component_name ] matches = [self.fs.exists(p) for p in possible_paths] if sum(matches): raise Exception(f"The file {path} can't be added as already found in the Drive.") def _validate_path(self, path: str) -> None: if not os.path.exists(os.path.join(self.root_folder, path)): raise FileExistsError(f"The provided path {path} doesn't exists") def __str__(self) -> str: assert self.id return self.id def _maybe_create_drive(component_name: str, state: Dict) -> Union[Dict, Drive]: if state.get("type") == Drive.__IDENTIFIER__: drive = Drive.from_dict(state) drive.component_name = component_name return drive return state
null
155,712
import hashlib import os import pathlib import shutil import sys from time import sleep from typing import TYPE_CHECKING, Any, List, Optional, Sequence, Union from fsspec import AbstractFileSystem from fsspec.implementations.local import LocalFileSystem from lightning.app.core.constants import REMOTE_STORAGE_WAIT from lightning.app.core.queues import BaseQueue from lightning.app.storage.requests import _ExistsRequest, _ExistsResponse, _GetRequest, _GetResponse from lightning.app.utilities.app_helpers import Logger from lightning.app.utilities.component import _is_flow_context from lightning.app.utilities.imports import _is_s3fs_available class Path(PathlibPath): """A drop-in replacement for :class:`pathlib.Path` for all paths in Lightning. The Lightning Path works exactly the same as :class:`pathlib.Path` but it also remembers in which LightningWork it was created. If the Path gets passed to a different LightningWork, the file or folder can then be easily accessed no matter where it is located in the other Work's filesystem. Args: *args: Accepts the same arguments as in :class:`pathlib.Path` **kwargs: Accepts the same keyword arguments as in :class:`pathlib.Path` """ def _from_parts(cls, args: Any, **__unused) -> "Path": """This gets called from the super class in ``pathlib.Path.__new__``. The Lightning Path overrides this to validate the instantiation in the case parts are passed in individually. In such a case we need to validate that all parts have the same `origin` and if not, an error is raised. """ if args and isinstance(args[0], str) and args[0].startswith("lit://"): parts = list(args) parts[0] = parts[0][len("lit://") :] args = (_storage_root_dir(), *parts) if (sys.version_info.major, sys.version_info.minor) < (3, 10): __unused.setdefault("init", True) new_path = super()._from_parts(args, **__unused) else: new_path = super()._from_parts(args) new_path._init_attributes() # we use this instead of defining a __init__() method paths_from_parts = [part for part in args if isinstance(part, Path)] if not paths_from_parts: return new_path top_path = paths_from_parts[0] origins = [part._origin for part in paths_from_parts] if not all(origins[0] == origin or origin is None for origin in origins): raise TypeError( "Tried to instantiate a Lightning Path from multiple other Paths that originate from different" " LightningWork." ) new_path._copy_properties_from(top_path) return new_path def _init_attributes(self): self._name: Optional[str] = None # the origin is the work that created this Path and wants to expose file(s) self._origin: Optional[Union["LightningWork", str]] = None # the consumer is the Work that needs access to the file(s) from the consumer self._consumer: Optional[Union["LightningWork", str]] = None self._metadata = {} # request queue: used to transfer message to storage orchestrator self._request_queue: Optional[BaseQueue] = None # response queue: used to receive status message from storage orchestrator self._response_queue: Optional[BaseQueue] = None def origin_name(self) -> str: """The name of the LightningWork where this path was first created. Attaching a Path to a LightningWork will automatically make it the `origin`. """ from lightning.app.core.work import LightningWork return self._origin.name if isinstance(self._origin, LightningWork) else self._origin def consumer_name(self) -> str: """The name of the LightningWork where this path is being accessed. By default, this is the same as the :attr:`origin_name`. """ from lightning.app.core.work import LightningWork return self._consumer.name if isinstance(self._consumer, LightningWork) else self._consumer def hash(self) -> Optional[str]: """The hash of this Path uniquely identifies the file path and the associated origin Work. Returns ``None`` if the origin is not defined, i.e., this Path did not yet get attached to a LightningWork. """ if self._origin is None: return None contents = f"{self.origin_name}/{self}" return hashlib.sha1(contents.encode("utf-8")).hexdigest() def parents(self) -> Sequence["Path"]: parents: List["Path"] = list(super().parents) for parent in parents: parent._copy_properties_from(self) return parents def parent(self) -> "Path": parent: Path = super().parent parent._copy_properties_from(self) return parent def exists(self) -> bool: """Check if the path exists locally or remotely. If the path exists locally, this method immediately returns ``True``, otherwise it will make a RPC call to the attached origin Work and check if the path exists remotely. If you strictly want to check local existence only, use :meth:`exists_local` instead. If you strictly want to check existence on the remote (regardless of whether the file exists locally or not), use :meth:`exists_remote`. """ return self.exists_local() or (self._origin and self.exists_remote()) def exists_local(self) -> bool: """Check if the path exists locally.""" return super().exists() def exists_remote(self) -> bool: """Check if the path exists remotely on the attached orgin Work. Raises: RuntimeError: If the path is not attached to any Work (origin undefined). """ # Fail early if we need to check the remote but an origin is not defined if not self._origin or self._request_queue is None or self._response_queue is None: raise RuntimeError( f"Trying to check if the file {self} exists, but the path is not attached to a LightningWork." f" Set it as an attribute to a LightningWork or pass it to the `run()` method." ) # 1. Send message to orchestrator through queue that with a request for a path existence check request = _ExistsRequest(source=self.origin_name, path=str(self), name=self._name, hash=self.hash) self._request_queue.put(request) # 2. Wait for the response to come back response: _ExistsResponse = self._response_queue.get() # blocking return response.exists def get(self, overwrite: bool = False) -> None: if _is_flow_context(): raise RuntimeError("`Path.get()` can only be called from within the `run()` method of LightningWork.") if self._request_queue is None or self._response_queue is None: raise RuntimeError( f"Trying to get the file {self}, but the path is not attached to a LightningApp." f" Are you trying to get the file from within `__init__`?" ) if self._origin is None: raise RuntimeError( f"Trying to get the file {self}, but the path is not attached to a LightningWork. Set it as an" f" attribute to a LightningWork or pass it to the `run()` method." ) if self.exists_local() and not overwrite: raise FileExistsError( f"The file or folder {self} exists locally. Pass `overwrite=True` if you wish to replace it" f" with the new contents." ) # 1. Send message to orchestrator through queue with details of the transfer # the source is the name of the work that owns the file that we request # the destination is determined by the queue, since each work has a dedicated send and recv queue request = _GetRequest(source=self.origin_name, path=str(self), hash=self.hash, name=self._name) self._request_queue.put(request) # 2. Wait for the transfer to finish response: _GetResponse = self._response_queue.get() # blocking self._validate_get_response(response) fs = _filesystem() # 3. Wait until the file appears in shared storage while not fs.exists(response.path) or fs.info(response.path)["size"] != response.size: sleep(REMOTE_STORAGE_WAIT) if self.exists_local() and self.is_dir(): # Delete the directory, otherwise we can't overwrite it shutil.rmtree(self) # 4. Copy the file from the shared storage to the destination on the local filesystem if fs.isdir(response.path): if isinstance(fs, LocalFileSystem): shutil.copytree(response.path, self.resolve()) else: glob = f"{str(response.path)}/**" _logger.debug(f"Attempting to copy {glob} -> {str(self.absolute())}") fs.get(glob, str(self.absolute()), recursive=False) else: _logger.debug(f"Attempting to copy {str(response.path)} -> {str(self.absolute())}") fs.get(str(response.path), str(self.absolute()), recursive=False) def to_dict(self) -> dict: """Serialize this Path to a dictionary.""" return { "path": str(self), "origin_name": self.origin_name, "consumer_name": self.consumer_name, "metadata": self._metadata, } def from_dict(cls, content: dict) -> "Path": """Instantiate a Path from a dictionary.""" path = cls(content["path"]) path._origin = content["origin_name"] path._consumer = content["consumer_name"] path._metadata = content["metadata"] return path def _validate_get_response(self, response: "_GetResponse") -> None: if response.source != self._origin or response.hash != self.hash: raise RuntimeError( f"Tried to get the file {self} but received a response for a request it did not send. The response" f" contents are: {response}" ) if response.exception is not None: raise RuntimeError( f"An exception was raised while trying to transfer the contents at {response.path}" f" from Work {response.source} to {response.destination}. See the full stacktrace above." ) from response.exception def _attach_work(self, work: "LightningWork") -> None: """Attach a LightningWork to this Path. The first work to be attached becomes the `origin`, i.e., the Work that is meant to expose the file to other Work. Attaching a Work to a Path that already has an `origin` Work will make it a `consumer`. A consumer Work is a work that can access the file only by first transferring it via :meth:`transfer`. Args: work: LightningWork to be attached to this Path. """ if self._origin is None: # Can become an owner only if there is not already one self._origin = work self._consumer = work def _attach_queues(self, request_queue: BaseQueue, response_queue: BaseQueue) -> None: """Attaches the queues for communication with the Storage Orchestrator.""" self._request_queue = request_queue self._response_queue = response_queue def _sanitize(self) -> None: """Sanitize this Path so that it can be deep-copied.""" self._origin = self.origin_name self._consumer = self.consumer_name self._request_queue = None self._response_queue = None def _copy_properties_from(self, other: "Path") -> None: self._origin = other._origin self._consumer = other._consumer self._metadata = other._metadata self._request_queue = other._request_queue self._response_queue = other._response_queue def with_name(self, name: str) -> "Path": path: Path = super().with_name(name) path._copy_properties_from(self) return path def with_stem(self, stem: str) -> "Path": path: Path = super().with_stem(stem) path._copy_properties_from(self) return path def with_suffix(self, suffix: str) -> "Path": path: Path = super().with_suffix(suffix) path._copy_properties_from(self) return path def relative_to(self, *other) -> "Path": path: Path = super().relative_to(*other) path._copy_properties_from(self) return path def __truediv__(self, other: Union["Path", PathlibPath, str]) -> "Path": path: Path = super().__truediv__(other) path._copy_properties_from(self) return path def __rtruediv__(self, other: Union["Path", PathlibPath, str]) -> "Path": path: Path = super().__rtruediv__(other) path._copy_properties_from(self) return path def __reduce__(self): return Path.from_dict, (self.to_dict(),) def __json__(self) -> dict: """Converts the Path to a json-serializable dict object.""" return self.to_dict() def _handle_exists_request(work: "LightningWork", request: _ExistsRequest) -> _ExistsResponse: return _ExistsResponse( source=request.source, name=request.name, hash=request.hash, path=request.path, destination=request.destination, exists=os.path.exists(request.path), ) def _handle_get_request(work: "LightningWork", request: _GetRequest) -> _GetResponse: from lightning.app.storage.copier import _copy_files source_path = pathlib.Path(request.path) destination_path = _shared_storage_path() / request.hash response = _GetResponse( source=request.source, name=request.name, path=str(destination_path), hash=request.hash, size=source_path.stat().st_size, destination=request.destination, ) try: _copy_files(source_path, destination_path) _logger.debug(f"All files copied from {request.path} to {response.path}.") except Exception as ex: response.exception = ex return response def _storage_root_dir() -> pathlib.Path: path = pathlib.Path(os.environ.get("STORAGE_ROOT_DIR", "./.storage")).absolute() path.mkdir(parents=True, exist_ok=True) return path def _is_lit_path(path: Union[str, Path]) -> bool: path = Path(path) return path == _storage_root_dir() or _storage_root_dir() in path.parents
null
155,713
import os import shutil from pathlib import Path from typing import Callable, List from fsspec.implementations.local import LocalFileSystem from lightning.app.storage.copier import _copy_files from lightning.app.storage.path import _filesystem, _shared_storage_path def _get_files(fs, src: Path, dst: Path, overwrite: bool = True): dst = dst.resolve() if fs.isdir(src): if isinstance(fs, LocalFileSystem): dst = dst.resolve() if fs.exists(dst): if overwrite: fs.rm(str(dst), recursive=True) else: raise FileExistsError(f"The file {dst} was found. Add get(..., overwrite=True) to replace it.") shutil.copytree(src, dst) else: glob = f"{str(src)}/**" fs.get(glob, str(dst), recursive=False) else: fs.get(str(src), str(dst), recursive=False)
null
155,714
import concurrent.futures import pathlib import threading from threading import Thread from time import time from typing import TYPE_CHECKING, Optional, Union from fsspec import AbstractFileSystem from fsspec.implementations.local import LocalFileSystem from lightning.app.core.queues import BaseQueue from lightning.app.storage.path import _filesystem from lightning.app.storage.requests import _ExistsRequest, _GetRequest from lightning.app.utilities.app_helpers import Logger class _GetRequest: source: str name: str path: str hash: str destination: str = "" def _find_matching_path(work, request: _GetRequest) -> Optional["lightning.app.storage.path.Path"]: for name in work._paths: candidate: lightning.app.storage.path.Path = getattr(work, name) if candidate.hash == request.hash: return candidate return None
null
155,715
import os from typing import List from lightning_cloud.openapi import V1Model, V1UploadModelRequest from lightning.app.utilities.cloud import _get_project from lightning.store.utils import _Client, _download_file_from_url, _upload_file_to_url def _get_project(client: LightningClient, project_id: Optional[str] = None, verbose: bool = True) -> V1Membership: """Get a project membership for the user from the backend.""" if project_id is None: project_id = LIGHTNING_CLOUD_PROJECT_ID if project_id is not None: project = client.projects_service_get_project(project_id) if not project: raise ValueError( "Environment variable `LIGHTNING_CLOUD_PROJECT_ID` is set but could not find an associated project." ) return V1Membership( name=project.name, display_name=project.display_name, description=project.description, created_at=project.created_at, project_id=project.id, owner_id=project.owner_id, owner_type=project.owner_type, quotas=project.quotas, updated_at=project.updated_at, ) projects = client.projects_service_list_memberships() if len(projects.memberships) == 0: raise ValueError("No valid projects found. Please reach out to lightning.ai team to create a project") if len(projects.memberships) > 1 and verbose: print(f"Defaulting to the project: {projects.memberships[0].name}") return projects.memberships[0] def _upload_file_to_url(url: str, path: str, progress_bar: bool) -> None: if progress_bar: file_size = os.path.getsize(path) with open(path, "rb") as fd, tqdm( desc="Uploading", total=file_size, unit="B", unit_scale=True, unit_divisor=1000, ) as t: reader_wrapper = CallbackIOWrapper(t.update, fd, "read") response = requests.put(url, data=reader_wrapper) response.raise_for_status() else: with open(path, "rb") as fo: requests.put(url, data=fo) class _Client(AuthServiceApi, ModelsStoreApi, ProjectsServiceApi): def __init__(self): api_client = create_swagger_client() super().__init__(api_client) The provided code snippet includes necessary dependencies for implementing the `upload_model` function. Write a Python function `def upload_model( name: str, path: str, version: str = "latest", progress_bar: bool = True, ) -> None` to solve the following problem: Upload a model to the lightning cloud. Args: name: The model name. path: The path to the checkpoint to be uploaded. version: The version of the model to be uploaded. If not provided, default will be latest (not overridden). progress_bar: A progress bar to show the uploading status. Disable this if not needed, by setting to `False`. Here is the function: def upload_model( name: str, path: str, version: str = "latest", progress_bar: bool = True, ) -> None: """Upload a model to the lightning cloud. Args: name: The model name. path: The path to the checkpoint to be uploaded. version: The version of the model to be uploaded. If not provided, default will be latest (not overridden). progress_bar: A progress bar to show the uploading status. Disable this if not needed, by setting to `False`. """ client = _Client() user = client.auth_service_get_user() # TODO: Allow passing this project_id = _get_project(client).project_id # TODO: Post model parts if the file size is over threshold body = V1UploadModelRequest( name=f"{user.username}/{name}", version=version, project_id=project_id, ) model = client.models_store_upload_model(body) _upload_file_to_url(model.upload_url, path, progress_bar=progress_bar)
Upload a model to the lightning cloud. Args: name: The model name. path: The path to the checkpoint to be uploaded. version: The version of the model to be uploaded. If not provided, default will be latest (not overridden). progress_bar: A progress bar to show the uploading status. Disable this if not needed, by setting to `False`.
155,716
import os from typing import List from lightning_cloud.openapi import V1Model, V1UploadModelRequest from lightning.app.utilities.cloud import _get_project from lightning.store.utils import _Client, _download_file_from_url, _upload_file_to_url def _download_file_from_url(url: str, path: str, progress_bar: bool) -> None: with requests.get(url, stream=True) as req_stream: total_size_in_bytes = int(req_stream.headers.get("content-length", 0)) block_size = 1000 * 1000 # 1 MB download_progress_bar = None if progress_bar: download_progress_bar = tqdm( desc="Downloading", total=total_size_in_bytes, unit="B", unit_scale=True, unit_divisor=1000, ) with open(path, "wb") as f: for chunk in req_stream.iter_content(chunk_size=block_size): if download_progress_bar: download_progress_bar.update(len(chunk)) f.write(chunk) if download_progress_bar: download_progress_bar.close() class _Client(AuthServiceApi, ModelsStoreApi, ProjectsServiceApi): def __init__(self): api_client = create_swagger_client() super().__init__(api_client) The provided code snippet includes necessary dependencies for implementing the `download_model` function. Write a Python function `def download_model( name: str, path: str, version: str = "latest", progress_bar: bool = True, ) -> None` to solve the following problem: Download a model from the lightning cloud. Args: name: The unique name of the model to be downloaded. Format: `<username>/<model_name>`. path: The path to download the model to. version: The version of the model to be uploaded. If not provided, default will be latest (not overridden). progress_bar: Show progress on download. Here is the function: def download_model( name: str, path: str, version: str = "latest", progress_bar: bool = True, ) -> None: """Download a model from the lightning cloud. Args: name: The unique name of the model to be downloaded. Format: `<username>/<model_name>`. path: The path to download the model to. version: The version of the model to be uploaded. If not provided, default will be latest (not overridden). progress_bar: Show progress on download. """ client = _Client() download_url = client.models_store_download_model(name=name, version=version).download_url _download_file_from_url(download_url, os.path.abspath(path), progress_bar=progress_bar)
Download a model from the lightning cloud. Args: name: The unique name of the model to be downloaded. Format: `<username>/<model_name>`. path: The path to download the model to. version: The version of the model to be uploaded. If not provided, default will be latest (not overridden). progress_bar: Show progress on download.
155,717
import os from typing import List from lightning_cloud.openapi import V1Model, V1UploadModelRequest from lightning.app.utilities.cloud import _get_project from lightning.store.utils import _Client, _download_file_from_url, _upload_file_to_url def _get_project(client: LightningClient, project_id: Optional[str] = None, verbose: bool = True) -> V1Membership: """Get a project membership for the user from the backend.""" if project_id is None: project_id = LIGHTNING_CLOUD_PROJECT_ID if project_id is not None: project = client.projects_service_get_project(project_id) if not project: raise ValueError( "Environment variable `LIGHTNING_CLOUD_PROJECT_ID` is set but could not find an associated project." ) return V1Membership( name=project.name, display_name=project.display_name, description=project.description, created_at=project.created_at, project_id=project.id, owner_id=project.owner_id, owner_type=project.owner_type, quotas=project.quotas, updated_at=project.updated_at, ) projects = client.projects_service_list_memberships() if len(projects.memberships) == 0: raise ValueError("No valid projects found. Please reach out to lightning.ai team to create a project") if len(projects.memberships) > 1 and verbose: print(f"Defaulting to the project: {projects.memberships[0].name}") return projects.memberships[0] class _Client(AuthServiceApi, ModelsStoreApi, ProjectsServiceApi): def __init__(self): api_client = create_swagger_client() super().__init__(api_client) The provided code snippet includes necessary dependencies for implementing the `list_models` function. Write a Python function `def list_models() -> List[V1Model]` to solve the following problem: List your models in the lightning cloud. Returns: A list of model objects. Here is the function: def list_models() -> List[V1Model]: """List your models in the lightning cloud. Returns: A list of model objects. """ client = _Client() # TODO: Allow passing this project_id = _get_project(client).project_id return client.models_store_list_models(project_id=project_id).models
List your models in the lightning cloud. Returns: A list of model objects.
155,718
import glob import os from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from types import ModuleType from typing import Any, Dict from pkg_resources import parse_requirements from setuptools import find_packages _PACKAGE_ROOT = os.path.join(_SOURCE_ROOT, "lightning_fabric") _PATH_REQUIREMENTS = os.path.join("requirements", "fabric") _FREEZE_REQUIREMENTS = os.environ.get("FREEZE_REQUIREMENTS", "0").lower() in ("1", "true") def _load_py_module(name: str, location: str) -> ModuleType: def _load_assistant() -> ModuleType: def _prepare_extras() -> Dict[str, Any]: def _setup_args() -> Dict[str, Any]: assistant = _load_assistant() about = _load_py_module("about", os.path.join(_PACKAGE_ROOT, "__about__.py")) version = _load_py_module("version", os.path.join(_PACKAGE_ROOT, "__version__.py")) long_description = assistant.load_readme_description( _PACKAGE_ROOT, homepage=about.__homepage__, version=version.version ) return { "name": "lightning-fabric", "version": version.version, "description": about.__docs__, "author": about.__author__, "author_email": about.__author_email__, "url": about.__homepage__, "download_url": "https://github.com/Lightning-AI/lightning", "license": about.__license__, "packages": find_packages(where="src", include=["lightning_fabric", "lightning_fabric.*"]), "package_dir": {"": "src"}, "long_description": long_description, "long_description_content_type": "text/markdown", "include_package_data": True, "zip_safe": False, "keywords": ["deep learning", "pytorch", "AI"], "python_requires": ">=3.8", "setup_requires": ["wheel"], "install_requires": assistant.load_requirements( _PATH_REQUIREMENTS, unfreeze="none" if _FREEZE_REQUIREMENTS else "all" ), "entry_points": { "console_scripts": [ "fabric = lightning_fabric.cli:_main", ], }, "extras_require": _prepare_extras(), "project_urls": { "Bug Tracker": "https://github.com/Lightning-AI/lightning/issues", "Documentation": "https://pytorch-lightning.rtfd.io/en/latest/", "Source Code": "https://github.com/Lightning-AI/lightning", }, "classifiers": [ "Environment :: Console", "Natural Language :: English", # How mature is this project? Common values are # 3 - Alpha, 4 - Beta, 5 - Production/Stable "Development Status :: 4 - Beta", # Indicate who your project is intended for "Intended Audience :: Developers", "Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: Scientific/Engineering :: Information Analysis", # Pick your license as you wish # 'License :: OSI Approved :: BSD License', "Operating System :: OS Independent", # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", ], }
null
155,719
import base64 from dataclasses import dataclass from io import BytesIO from os import path from typing import Dict, Optional import numpy as np import torch import torchvision import torchvision.transforms as T from lightning.pytorch import LightningDataModule, LightningModule, cli_lightning_logo from lightning.pytorch.cli import LightningCLI from lightning.pytorch.serve import ServableModule, ServableModuleValidator from lightning.pytorch.utilities.model_helpers import get_torchvision_model from PIL import Image as PILImage class CIFAR10DataModule(LightningDataModule): transform = T.Compose([T.Resize(256), T.CenterCrop(224), T.ToTensor()]) def train_dataloader(self, *args, **kwargs): trainset = torchvision.datasets.CIFAR10(root=DATASETS_PATH, train=True, download=True, transform=self.transform) return torch.utils.data.DataLoader(trainset, batch_size=2, shuffle=True, num_workers=0) def val_dataloader(self, *args, **kwargs): valset = torchvision.datasets.CIFAR10(root=DATASETS_PATH, train=False, download=True, transform=self.transform) return torch.utils.data.DataLoader(valset, batch_size=2, shuffle=True, num_workers=0) class ProductionReadyModel(LitModule, ServableModule): def configure_payload(self): # 1: Access the train dataloader and load a single sample. image, _ = self.trainer.train_dataloader.dataset[0] # 2: Convert the image into a PIL Image to bytes and encode it with base64 pil_image = T.ToPILImage()(image) buffered = BytesIO() pil_image.save(buffered, format="JPEG") img_str = base64.b64encode(buffered.getvalue()).decode("UTF-8") return {"body": {"x": img_str}} def configure_serialization(self): return {"x": Image(224, 224).deserialize}, {"output": Top1().serialize} def serve_step(self, x: torch.Tensor) -> Dict[str, torch.Tensor]: return {"output": self.model(x)} def configure_response(self): return {"output": 7} class LightningCLI: """Implementation of a configurable command line tool for pytorch-lightning.""" def __init__( self, model_class: Optional[Union[Type[LightningModule], Callable[..., LightningModule]]] = None, datamodule_class: Optional[Union[Type[LightningDataModule], Callable[..., LightningDataModule]]] = None, save_config_callback: Optional[Type[SaveConfigCallback]] = SaveConfigCallback, save_config_kwargs: Optional[Dict[str, Any]] = None, trainer_class: Union[Type[Trainer], Callable[..., Trainer]] = Trainer, trainer_defaults: Optional[Dict[str, Any]] = None, seed_everything_default: Union[bool, int] = True, parser_kwargs: Optional[Union[Dict[str, Any], Dict[str, Dict[str, Any]]]] = None, subclass_mode_model: bool = False, subclass_mode_data: bool = False, args: ArgsType = None, run: bool = True, auto_configure_optimizers: bool = True, ) -> None: """Receives as input pytorch-lightning classes (or callables which return pytorch-lightning classes), which are called / instantiated using a parsed configuration file and / or command line args. Parsing of configuration from environment variables can be enabled by setting ``parser_kwargs={"default_env": True}``. A full configuration yaml would be parsed from ``PL_CONFIG`` if set. Individual settings are so parsed from variables named for example ``PL_TRAINER__MAX_EPOCHS``. For more info, read :ref:`the CLI docs <lightning-cli>`. Args: model_class: An optional :class:`~lightning.pytorch.core.LightningModule` class to train on or a callable which returns a :class:`~lightning.pytorch.core.LightningModule` instance when called. If ``None``, you can pass a registered model with ``--model=MyModel``. datamodule_class: An optional :class:`~lightning.pytorch.core.datamodule.LightningDataModule` class or a callable which returns a :class:`~lightning.pytorch.core.datamodule.LightningDataModule` instance when called. If ``None``, you can pass a registered datamodule with ``--data=MyDataModule``. save_config_callback: A callback class to save the config. save_config_kwargs: Parameters that will be used to instantiate the save_config_callback. trainer_class: An optional subclass of the :class:`~lightning.pytorch.trainer.trainer.Trainer` class or a callable which returns a :class:`~lightning.pytorch.trainer.trainer.Trainer` instance when called. trainer_defaults: Set to override Trainer defaults or add persistent callbacks. The callbacks added through this argument will not be configurable from a configuration file and will always be present for this particular CLI. Alternatively, configurable callbacks can be added as explained in :ref:`the CLI docs <lightning-cli>`. seed_everything_default: Number for the :func:`~lightning.fabric.utilities.seed.seed_everything` seed value. Set to True to automatically choose a seed value. Setting it to False will avoid calling ``seed_everything``. parser_kwargs: Additional arguments to instantiate each ``LightningArgumentParser``. subclass_mode_model: Whether model can be any `subclass <https://jsonargparse.readthedocs.io/en/stable/#class-type-and-sub-classes>`_ of the given class. subclass_mode_data: Whether datamodule can be any `subclass <https://jsonargparse.readthedocs.io/en/stable/#class-type-and-sub-classes>`_ of the given class. args: Arguments to parse. If ``None`` the arguments are taken from ``sys.argv``. Command line style arguments can be given in a ``list``. Alternatively, structured config options can be given in a ``dict`` or ``jsonargparse.Namespace``. run: Whether subcommands should be added to run a :class:`~lightning.pytorch.trainer.trainer.Trainer` method. If set to ``False``, the trainer and model classes will be instantiated only. """ self.save_config_callback = save_config_callback self.save_config_kwargs = save_config_kwargs or {} self.trainer_class = trainer_class self.trainer_defaults = trainer_defaults or {} self.seed_everything_default = seed_everything_default self.parser_kwargs = parser_kwargs or {} self.auto_configure_optimizers = auto_configure_optimizers self.model_class = model_class # used to differentiate between the original value and the processed value self._model_class = model_class or LightningModule self.subclass_mode_model = (model_class is None) or subclass_mode_model self.datamodule_class = datamodule_class # used to differentiate between the original value and the processed value self._datamodule_class = datamodule_class or LightningDataModule self.subclass_mode_data = (datamodule_class is None) or subclass_mode_data main_kwargs, subparser_kwargs = self._setup_parser_kwargs(self.parser_kwargs) self.setup_parser(run, main_kwargs, subparser_kwargs) self.parse_arguments(self.parser, args) self.subcommand = self.config["subcommand"] if run else None self._set_seed() self._add_instantiators() self.before_instantiate_classes() self.instantiate_classes() if self.subcommand is not None: self._run_subcommand(self.subcommand) def _setup_parser_kwargs(self, parser_kwargs: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]: subcommand_names = self.subcommands().keys() main_kwargs = {k: v for k, v in parser_kwargs.items() if k not in subcommand_names} subparser_kwargs = {k: v for k, v in parser_kwargs.items() if k in subcommand_names} return main_kwargs, subparser_kwargs def init_parser(self, **kwargs: Any) -> LightningArgumentParser: """Method that instantiates the argument parser.""" kwargs.setdefault("dump_header", [f"lightning.pytorch=={pl.__version__}"]) parser = LightningArgumentParser(**kwargs) parser.add_argument( "-c", "--config", action=ActionConfigFile, help="Path to a configuration file in json or yaml format." ) return parser def setup_parser( self, add_subcommands: bool, main_kwargs: Dict[str, Any], subparser_kwargs: Dict[str, Any] ) -> None: """Initialize and setup the parser, subcommands, and arguments.""" self.parser = self.init_parser(**main_kwargs) if add_subcommands: self._subcommand_method_arguments: Dict[str, List[str]] = {} self._add_subcommands(self.parser, **subparser_kwargs) else: self._add_arguments(self.parser) def add_default_arguments_to_parser(self, parser: LightningArgumentParser) -> None: """Adds default arguments to the parser.""" parser.add_argument( "--seed_everything", type=Union[bool, int], default=self.seed_everything_default, help=( "Set to an int to run seed_everything with this value before classes instantiation." "Set to True to use a random seed." ), ) def add_core_arguments_to_parser(self, parser: LightningArgumentParser) -> None: """Adds arguments from the core classes to the parser.""" parser.add_lightning_class_args(self.trainer_class, "trainer") trainer_defaults = {"trainer." + k: v for k, v in self.trainer_defaults.items() if k != "callbacks"} parser.set_defaults(trainer_defaults) parser.add_lightning_class_args(self._model_class, "model", subclass_mode=self.subclass_mode_model) if self.datamodule_class is not None: parser.add_lightning_class_args(self._datamodule_class, "data", subclass_mode=self.subclass_mode_data) else: # this should not be required because the user might want to use the `LightningModule` dataloaders parser.add_lightning_class_args( self._datamodule_class, "data", subclass_mode=self.subclass_mode_data, required=False ) def _add_arguments(self, parser: LightningArgumentParser) -> None: # default + core + custom arguments self.add_default_arguments_to_parser(parser) self.add_core_arguments_to_parser(parser) self.add_arguments_to_parser(parser) # add default optimizer args if necessary if self.auto_configure_optimizers: if not parser._optimizers: # already added by the user in `add_arguments_to_parser` parser.add_optimizer_args((Optimizer,)) if not parser._lr_schedulers: # already added by the user in `add_arguments_to_parser` parser.add_lr_scheduler_args(LRSchedulerTypeTuple) self.link_optimizers_and_lr_schedulers(parser) def add_arguments_to_parser(self, parser: LightningArgumentParser) -> None: """Implement to add extra arguments to the parser or link arguments. Args: parser: The parser object to which arguments can be added """ def subcommands() -> Dict[str, Set[str]]: """Defines the list of available subcommands and the arguments to skip.""" return { "fit": {"model", "train_dataloaders", "val_dataloaders", "datamodule"}, "validate": {"model", "dataloaders", "datamodule"}, "test": {"model", "dataloaders", "datamodule"}, "predict": {"model", "dataloaders", "datamodule"}, } def _add_subcommands(self, parser: LightningArgumentParser, **kwargs: Any) -> None: """Adds subcommands to the input parser.""" self._subcommand_parsers: Dict[str, LightningArgumentParser] = {} parser_subcommands = parser.add_subcommands() # the user might have passed a builder function trainer_class = ( self.trainer_class if isinstance(self.trainer_class, type) else class_from_function(self.trainer_class) ) # register all subcommands in separate subcommand parsers under the main parser for subcommand in self.subcommands(): fn = getattr(trainer_class, subcommand) # extract the first line description in the docstring for the subcommand help message description = _get_short_description(fn) subparser_kwargs = kwargs.get(subcommand, {}) subparser_kwargs.setdefault("description", description) subcommand_parser = self._prepare_subcommand_parser(trainer_class, subcommand, **subparser_kwargs) self._subcommand_parsers[subcommand] = subcommand_parser parser_subcommands.add_subcommand(subcommand, subcommand_parser, help=description) def _prepare_subcommand_parser(self, klass: Type, subcommand: str, **kwargs: Any) -> LightningArgumentParser: parser = self.init_parser(**kwargs) self._add_arguments(parser) # subcommand arguments skip: Set[Union[str, int]] = set(self.subcommands()[subcommand]) added = parser.add_method_arguments(klass, subcommand, skip=skip) # need to save which arguments were added to pass them to the method later self._subcommand_method_arguments[subcommand] = added return parser def link_optimizers_and_lr_schedulers(parser: LightningArgumentParser) -> None: """Creates argument links for optimizers and learning rate schedulers that specified a ``link_to``.""" optimizers_and_lr_schedulers = {**parser._optimizers, **parser._lr_schedulers} for key, (class_type, link_to) in optimizers_and_lr_schedulers.items(): if link_to == "AUTOMATIC": continue if isinstance(class_type, tuple): parser.link_arguments(key, link_to) else: add_class_path = _add_class_path_generator(class_type) parser.link_arguments(key, link_to, compute_fn=add_class_path) def parse_arguments(self, parser: LightningArgumentParser, args: ArgsType) -> None: """Parses command line arguments and stores it in ``self.config``.""" if args is not None and len(sys.argv) > 1: rank_zero_warn( "LightningCLI's args parameter is intended to run from within Python like if it were from the command " "line. To prevent mistakes it is not recommended to provide both args and command line arguments, got: " f"sys.argv[1:]={sys.argv[1:]}, args={args}." ) if isinstance(args, (dict, Namespace)): self.config = parser.parse_object(args) else: self.config = parser.parse_args(args) def _add_instantiators(self) -> None: self.config_dump = yaml.safe_load(self.parser.dump(self.config, skip_link_targets=False)) if "subcommand" in self.config: self.config_dump = self.config_dump[self.config.subcommand] self.parser.add_instantiator( _InstantiatorFn(cli=self, key="model"), _get_module_type(self._model_class), subclasses=self.subclass_mode_model, ) self.parser.add_instantiator( _InstantiatorFn(cli=self, key="data"), _get_module_type(self._datamodule_class), subclasses=self.subclass_mode_data, ) def before_instantiate_classes(self) -> None: """Implement to run some code before instantiating the classes.""" def instantiate_classes(self) -> None: """Instantiates the classes and sets their attributes.""" self.config_init = self.parser.instantiate_classes(self.config) self.datamodule = self._get(self.config_init, "data") self.model = self._get(self.config_init, "model") self._add_configure_optimizers_method_to_model(self.subcommand) self.trainer = self.instantiate_trainer() def instantiate_trainer(self, **kwargs: Any) -> Trainer: """Instantiates the trainer. Args: kwargs: Any custom trainer arguments. """ extra_callbacks = [self._get(self.config_init, c) for c in self._parser(self.subcommand).callback_keys] trainer_config = {**self._get(self.config_init, "trainer", default={}), **kwargs} return self._instantiate_trainer(trainer_config, extra_callbacks) def _instantiate_trainer(self, config: Dict[str, Any], callbacks: List[Callback]) -> Trainer: key = "callbacks" if key in config: if config[key] is None: config[key] = [] elif not isinstance(config[key], list): config[key] = [config[key]] config[key].extend(callbacks) if key in self.trainer_defaults: value = self.trainer_defaults[key] config[key] += value if isinstance(value, list) else [value] if self.save_config_callback and not config.get("fast_dev_run", False): config_callback = self.save_config_callback( self._parser(self.subcommand), self.config.get(str(self.subcommand), self.config), **self.save_config_kwargs, ) config[key].append(config_callback) else: rank_zero_warn( f"The `{self.trainer_class.__qualname__}` class does not expose the `{key}` argument so they will" " not be included." ) return self.trainer_class(**config) def _parser(self, subcommand: Optional[str]) -> LightningArgumentParser: if subcommand is None: return self.parser # return the subcommand parser for the subcommand passed return self._subcommand_parsers[subcommand] def configure_optimizers( lightning_module: LightningModule, optimizer: Optimizer, lr_scheduler: Optional[LRSchedulerTypeUnion] = None ) -> Any: """Override to customize the :meth:`~lightning.pytorch.core.LightningModule.configure_optimizers` method. Args: lightning_module: A reference to the model. optimizer: The optimizer. lr_scheduler: The learning rate scheduler (if used). """ if lr_scheduler is None: return optimizer if isinstance(lr_scheduler, ReduceLROnPlateau): return { "optimizer": optimizer, "lr_scheduler": {"scheduler": lr_scheduler, "monitor": lr_scheduler.monitor}, } return [optimizer], [lr_scheduler] def _add_configure_optimizers_method_to_model(self, subcommand: Optional[str]) -> None: """Overrides the model's :meth:`~lightning.pytorch.core.LightningModule.configure_optimizers` method if a single optimizer and optionally a scheduler argument groups are added to the parser as 'AUTOMATIC'.""" if not self.auto_configure_optimizers: return parser = self._parser(subcommand) def get_automatic( class_type: Union[Type, Tuple[Type, ...]], register: Dict[str, Tuple[Union[Type, Tuple[Type, ...]], str]] ) -> List[str]: automatic = [] for key, (base_class, link_to) in register.items(): if not isinstance(base_class, tuple): base_class = (base_class,) if link_to == "AUTOMATIC" and any(issubclass(c, class_type) for c in base_class): automatic.append(key) return automatic optimizers = get_automatic(Optimizer, parser._optimizers) lr_schedulers = get_automatic(LRSchedulerTypeTuple, parser._lr_schedulers) if len(optimizers) == 0: return if len(optimizers) > 1 or len(lr_schedulers) > 1: raise MisconfigurationException( f"`{self.__class__.__name__}.add_configure_optimizers_method_to_model` expects at most one optimizer " f"and one lr_scheduler to be 'AUTOMATIC', but found {optimizers + lr_schedulers}. In this case the " "user is expected to link the argument groups and implement `configure_optimizers`, see " "https://lightning.ai/docs/pytorch/stable/common/lightning_cli.html" "#optimizers-and-learning-rate-schedulers" ) optimizer_class = parser._optimizers[optimizers[0]][0] optimizer_init = self._get(self.config_init, optimizers[0]) if not isinstance(optimizer_class, tuple): optimizer_init = _global_add_class_path(optimizer_class, optimizer_init) if not optimizer_init: # optimizers were registered automatically but not passed by the user return lr_scheduler_init = None if lr_schedulers: lr_scheduler_class = parser._lr_schedulers[lr_schedulers[0]][0] lr_scheduler_init = self._get(self.config_init, lr_schedulers[0]) if not isinstance(lr_scheduler_class, tuple): lr_scheduler_init = _global_add_class_path(lr_scheduler_class, lr_scheduler_init) if is_overridden("configure_optimizers", self.model): _warn( f"`{self.model.__class__.__name__}.configure_optimizers` will be overridden by " f"`{self.__class__.__name__}.configure_optimizers`." ) optimizer = instantiate_class(self.model.parameters(), optimizer_init) lr_scheduler = instantiate_class(optimizer, lr_scheduler_init) if lr_scheduler_init else None fn = partial(self.configure_optimizers, optimizer=optimizer, lr_scheduler=lr_scheduler) update_wrapper(fn, self.configure_optimizers) # necessary for `is_overridden` # override the existing method self.model.configure_optimizers = MethodType(fn, self.model) def _get(self, config: Namespace, key: str, default: Optional[Any] = None) -> Any: """Utility to get a config value which might be inside a subcommand.""" return config.get(str(self.subcommand), config).get(key, default) def _run_subcommand(self, subcommand: str) -> None: """Run the chosen subcommand.""" before_fn = getattr(self, f"before_{subcommand}", None) if callable(before_fn): before_fn() default = getattr(self.trainer, subcommand) fn = getattr(self, subcommand, default) fn_kwargs = self._prepare_subcommand_kwargs(subcommand) fn(**fn_kwargs) after_fn = getattr(self, f"after_{subcommand}", None) if callable(after_fn): after_fn() def _prepare_subcommand_kwargs(self, subcommand: str) -> Dict[str, Any]: """Prepares the keyword arguments to pass to the subcommand to run.""" fn_kwargs = { k: v for k, v in self.config_init[subcommand].items() if k in self._subcommand_method_arguments[subcommand] } fn_kwargs["model"] = self.model if self.datamodule is not None: fn_kwargs["datamodule"] = self.datamodule return fn_kwargs def _set_seed(self) -> None: """Sets the seed.""" config_seed = self._get(self.config, "seed_everything") if config_seed is False: return if config_seed is True: # user requested seeding, choose randomly config_seed = seed_everything(workers=True) else: config_seed = seed_everything(config_seed, workers=True) if self.subcommand: self.config[self.subcommand]["seed_everything"] = config_seed else: self.config["seed_everything"] = config_seed def cli_main(): cli = LightningCLI( ProductionReadyModel, CIFAR10DataModule, seed_everything_default=42, save_config_kwargs={"overwrite": True}, run=False, trainer_defaults={ "accelerator": "cpu", "callbacks": [ServableModuleValidator()], "max_epochs": 1, "limit_train_batches": 5, "limit_val_batches": 5, }, ) cli.trainer.fit(cli.model, cli.datamodule)
null
155,720
import os import torch from lightning.pytorch import LightningModule, Trainer from torch.utils.data import DataLoader, Dataset class RandomDataset(Dataset): def __init__(self, size, length): def __getitem__(self, index): def __len__(self): class BoringModel(LightningModule): def __init__(self): def forward(self, x): def training_step(self, batch, batch_idx): def validation_step(self, batch, batch_idx): def test_step(self, batch, batch_idx): def configure_optimizers(self): def run(): train_data = DataLoader(RandomDataset(32, 64), batch_size=2) val_data = DataLoader(RandomDataset(32, 64), batch_size=2) test_data = DataLoader(RandomDataset(32, 64), batch_size=2) model = BoringModel() trainer = Trainer( default_root_dir=os.getcwd(), limit_train_batches=1, limit_val_batches=1, limit_test_batches=1, num_sanity_val_steps=0, max_epochs=1, enable_model_summary=False, ) trainer.fit(model, train_dataloaders=train_data, val_dataloaders=val_data) trainer.test(model, dataloaders=test_data)
null
155,721
from os import path import torch import torchvision import torchvision.transforms as T from lightning.pytorch import LightningDataModule, LightningModule, cli_lightning_logo from lightning.pytorch.cli import LightningCLI from lightning.pytorch.profilers.pytorch import PyTorchProfiler from lightning.pytorch.utilities.model_helpers import get_torchvision_model class ModelToProfile(LightningModule): def __init__(self, name: str = "resnet18", automatic_optimization: bool = True): super().__init__() self.model = get_torchvision_model(name, weights="DEFAULT") self.criterion = torch.nn.CrossEntropyLoss() self.automatic_optimization = automatic_optimization self.training_step = ( self.automatic_optimization_training_step if automatic_optimization else self.manual_optimization_training_step ) def automatic_optimization_training_step(self, batch, batch_idx): inputs, labels = batch outputs = self.model(inputs) loss = self.criterion(outputs, labels) self.log("train_loss", loss) return loss def manual_optimization_training_step(self, batch, batch_idx): opt = self.optimizers() opt.zero_grad() inputs, labels = batch outputs = self.model(inputs) loss = self.criterion(outputs, labels) self.log("train_loss", loss) self.manual_backward(loss) opt.step() def validation_step(self, batch, batch_idx): inputs, labels = batch outputs = self.model(inputs) loss = self.criterion(outputs, labels) self.log("val_loss", loss) def predict_step(self, batch, batch_idx, dataloader_idx: int = None): inputs = batch[0] return self.model(inputs) def configure_optimizers(self): return torch.optim.SGD(self.parameters(), lr=0.001, momentum=0.9) class CIFAR10DataModule(LightningDataModule): transform = T.Compose([T.Resize(256), T.CenterCrop(224), T.ToTensor()]) def train_dataloader(self, *args, **kwargs): trainset = torchvision.datasets.CIFAR10(root=DATASETS_PATH, train=True, download=True, transform=self.transform) return torch.utils.data.DataLoader(trainset, batch_size=2, shuffle=True, num_workers=0) def val_dataloader(self, *args, **kwargs): valset = torchvision.datasets.CIFAR10(root=DATASETS_PATH, train=False, download=True, transform=self.transform) return torch.utils.data.DataLoader(valset, batch_size=2, shuffle=True, num_workers=0) class LightningCLI: """Implementation of a configurable command line tool for pytorch-lightning.""" def __init__( self, model_class: Optional[Union[Type[LightningModule], Callable[..., LightningModule]]] = None, datamodule_class: Optional[Union[Type[LightningDataModule], Callable[..., LightningDataModule]]] = None, save_config_callback: Optional[Type[SaveConfigCallback]] = SaveConfigCallback, save_config_kwargs: Optional[Dict[str, Any]] = None, trainer_class: Union[Type[Trainer], Callable[..., Trainer]] = Trainer, trainer_defaults: Optional[Dict[str, Any]] = None, seed_everything_default: Union[bool, int] = True, parser_kwargs: Optional[Union[Dict[str, Any], Dict[str, Dict[str, Any]]]] = None, subclass_mode_model: bool = False, subclass_mode_data: bool = False, args: ArgsType = None, run: bool = True, auto_configure_optimizers: bool = True, ) -> None: """Receives as input pytorch-lightning classes (or callables which return pytorch-lightning classes), which are called / instantiated using a parsed configuration file and / or command line args. Parsing of configuration from environment variables can be enabled by setting ``parser_kwargs={"default_env": True}``. A full configuration yaml would be parsed from ``PL_CONFIG`` if set. Individual settings are so parsed from variables named for example ``PL_TRAINER__MAX_EPOCHS``. For more info, read :ref:`the CLI docs <lightning-cli>`. Args: model_class: An optional :class:`~lightning.pytorch.core.LightningModule` class to train on or a callable which returns a :class:`~lightning.pytorch.core.LightningModule` instance when called. If ``None``, you can pass a registered model with ``--model=MyModel``. datamodule_class: An optional :class:`~lightning.pytorch.core.datamodule.LightningDataModule` class or a callable which returns a :class:`~lightning.pytorch.core.datamodule.LightningDataModule` instance when called. If ``None``, you can pass a registered datamodule with ``--data=MyDataModule``. save_config_callback: A callback class to save the config. save_config_kwargs: Parameters that will be used to instantiate the save_config_callback. trainer_class: An optional subclass of the :class:`~lightning.pytorch.trainer.trainer.Trainer` class or a callable which returns a :class:`~lightning.pytorch.trainer.trainer.Trainer` instance when called. trainer_defaults: Set to override Trainer defaults or add persistent callbacks. The callbacks added through this argument will not be configurable from a configuration file and will always be present for this particular CLI. Alternatively, configurable callbacks can be added as explained in :ref:`the CLI docs <lightning-cli>`. seed_everything_default: Number for the :func:`~lightning.fabric.utilities.seed.seed_everything` seed value. Set to True to automatically choose a seed value. Setting it to False will avoid calling ``seed_everything``. parser_kwargs: Additional arguments to instantiate each ``LightningArgumentParser``. subclass_mode_model: Whether model can be any `subclass <https://jsonargparse.readthedocs.io/en/stable/#class-type-and-sub-classes>`_ of the given class. subclass_mode_data: Whether datamodule can be any `subclass <https://jsonargparse.readthedocs.io/en/stable/#class-type-and-sub-classes>`_ of the given class. args: Arguments to parse. If ``None`` the arguments are taken from ``sys.argv``. Command line style arguments can be given in a ``list``. Alternatively, structured config options can be given in a ``dict`` or ``jsonargparse.Namespace``. run: Whether subcommands should be added to run a :class:`~lightning.pytorch.trainer.trainer.Trainer` method. If set to ``False``, the trainer and model classes will be instantiated only. """ self.save_config_callback = save_config_callback self.save_config_kwargs = save_config_kwargs or {} self.trainer_class = trainer_class self.trainer_defaults = trainer_defaults or {} self.seed_everything_default = seed_everything_default self.parser_kwargs = parser_kwargs or {} self.auto_configure_optimizers = auto_configure_optimizers self.model_class = model_class # used to differentiate between the original value and the processed value self._model_class = model_class or LightningModule self.subclass_mode_model = (model_class is None) or subclass_mode_model self.datamodule_class = datamodule_class # used to differentiate between the original value and the processed value self._datamodule_class = datamodule_class or LightningDataModule self.subclass_mode_data = (datamodule_class is None) or subclass_mode_data main_kwargs, subparser_kwargs = self._setup_parser_kwargs(self.parser_kwargs) self.setup_parser(run, main_kwargs, subparser_kwargs) self.parse_arguments(self.parser, args) self.subcommand = self.config["subcommand"] if run else None self._set_seed() self._add_instantiators() self.before_instantiate_classes() self.instantiate_classes() if self.subcommand is not None: self._run_subcommand(self.subcommand) def _setup_parser_kwargs(self, parser_kwargs: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]: subcommand_names = self.subcommands().keys() main_kwargs = {k: v for k, v in parser_kwargs.items() if k not in subcommand_names} subparser_kwargs = {k: v for k, v in parser_kwargs.items() if k in subcommand_names} return main_kwargs, subparser_kwargs def init_parser(self, **kwargs: Any) -> LightningArgumentParser: """Method that instantiates the argument parser.""" kwargs.setdefault("dump_header", [f"lightning.pytorch=={pl.__version__}"]) parser = LightningArgumentParser(**kwargs) parser.add_argument( "-c", "--config", action=ActionConfigFile, help="Path to a configuration file in json or yaml format." ) return parser def setup_parser( self, add_subcommands: bool, main_kwargs: Dict[str, Any], subparser_kwargs: Dict[str, Any] ) -> None: """Initialize and setup the parser, subcommands, and arguments.""" self.parser = self.init_parser(**main_kwargs) if add_subcommands: self._subcommand_method_arguments: Dict[str, List[str]] = {} self._add_subcommands(self.parser, **subparser_kwargs) else: self._add_arguments(self.parser) def add_default_arguments_to_parser(self, parser: LightningArgumentParser) -> None: """Adds default arguments to the parser.""" parser.add_argument( "--seed_everything", type=Union[bool, int], default=self.seed_everything_default, help=( "Set to an int to run seed_everything with this value before classes instantiation." "Set to True to use a random seed." ), ) def add_core_arguments_to_parser(self, parser: LightningArgumentParser) -> None: """Adds arguments from the core classes to the parser.""" parser.add_lightning_class_args(self.trainer_class, "trainer") trainer_defaults = {"trainer." + k: v for k, v in self.trainer_defaults.items() if k != "callbacks"} parser.set_defaults(trainer_defaults) parser.add_lightning_class_args(self._model_class, "model", subclass_mode=self.subclass_mode_model) if self.datamodule_class is not None: parser.add_lightning_class_args(self._datamodule_class, "data", subclass_mode=self.subclass_mode_data) else: # this should not be required because the user might want to use the `LightningModule` dataloaders parser.add_lightning_class_args( self._datamodule_class, "data", subclass_mode=self.subclass_mode_data, required=False ) def _add_arguments(self, parser: LightningArgumentParser) -> None: # default + core + custom arguments self.add_default_arguments_to_parser(parser) self.add_core_arguments_to_parser(parser) self.add_arguments_to_parser(parser) # add default optimizer args if necessary if self.auto_configure_optimizers: if not parser._optimizers: # already added by the user in `add_arguments_to_parser` parser.add_optimizer_args((Optimizer,)) if not parser._lr_schedulers: # already added by the user in `add_arguments_to_parser` parser.add_lr_scheduler_args(LRSchedulerTypeTuple) self.link_optimizers_and_lr_schedulers(parser) def add_arguments_to_parser(self, parser: LightningArgumentParser) -> None: """Implement to add extra arguments to the parser or link arguments. Args: parser: The parser object to which arguments can be added """ def subcommands() -> Dict[str, Set[str]]: """Defines the list of available subcommands and the arguments to skip.""" return { "fit": {"model", "train_dataloaders", "val_dataloaders", "datamodule"}, "validate": {"model", "dataloaders", "datamodule"}, "test": {"model", "dataloaders", "datamodule"}, "predict": {"model", "dataloaders", "datamodule"}, } def _add_subcommands(self, parser: LightningArgumentParser, **kwargs: Any) -> None: """Adds subcommands to the input parser.""" self._subcommand_parsers: Dict[str, LightningArgumentParser] = {} parser_subcommands = parser.add_subcommands() # the user might have passed a builder function trainer_class = ( self.trainer_class if isinstance(self.trainer_class, type) else class_from_function(self.trainer_class) ) # register all subcommands in separate subcommand parsers under the main parser for subcommand in self.subcommands(): fn = getattr(trainer_class, subcommand) # extract the first line description in the docstring for the subcommand help message description = _get_short_description(fn) subparser_kwargs = kwargs.get(subcommand, {}) subparser_kwargs.setdefault("description", description) subcommand_parser = self._prepare_subcommand_parser(trainer_class, subcommand, **subparser_kwargs) self._subcommand_parsers[subcommand] = subcommand_parser parser_subcommands.add_subcommand(subcommand, subcommand_parser, help=description) def _prepare_subcommand_parser(self, klass: Type, subcommand: str, **kwargs: Any) -> LightningArgumentParser: parser = self.init_parser(**kwargs) self._add_arguments(parser) # subcommand arguments skip: Set[Union[str, int]] = set(self.subcommands()[subcommand]) added = parser.add_method_arguments(klass, subcommand, skip=skip) # need to save which arguments were added to pass them to the method later self._subcommand_method_arguments[subcommand] = added return parser def link_optimizers_and_lr_schedulers(parser: LightningArgumentParser) -> None: """Creates argument links for optimizers and learning rate schedulers that specified a ``link_to``.""" optimizers_and_lr_schedulers = {**parser._optimizers, **parser._lr_schedulers} for key, (class_type, link_to) in optimizers_and_lr_schedulers.items(): if link_to == "AUTOMATIC": continue if isinstance(class_type, tuple): parser.link_arguments(key, link_to) else: add_class_path = _add_class_path_generator(class_type) parser.link_arguments(key, link_to, compute_fn=add_class_path) def parse_arguments(self, parser: LightningArgumentParser, args: ArgsType) -> None: """Parses command line arguments and stores it in ``self.config``.""" if args is not None and len(sys.argv) > 1: rank_zero_warn( "LightningCLI's args parameter is intended to run from within Python like if it were from the command " "line. To prevent mistakes it is not recommended to provide both args and command line arguments, got: " f"sys.argv[1:]={sys.argv[1:]}, args={args}." ) if isinstance(args, (dict, Namespace)): self.config = parser.parse_object(args) else: self.config = parser.parse_args(args) def _add_instantiators(self) -> None: self.config_dump = yaml.safe_load(self.parser.dump(self.config, skip_link_targets=False)) if "subcommand" in self.config: self.config_dump = self.config_dump[self.config.subcommand] self.parser.add_instantiator( _InstantiatorFn(cli=self, key="model"), _get_module_type(self._model_class), subclasses=self.subclass_mode_model, ) self.parser.add_instantiator( _InstantiatorFn(cli=self, key="data"), _get_module_type(self._datamodule_class), subclasses=self.subclass_mode_data, ) def before_instantiate_classes(self) -> None: """Implement to run some code before instantiating the classes.""" def instantiate_classes(self) -> None: """Instantiates the classes and sets their attributes.""" self.config_init = self.parser.instantiate_classes(self.config) self.datamodule = self._get(self.config_init, "data") self.model = self._get(self.config_init, "model") self._add_configure_optimizers_method_to_model(self.subcommand) self.trainer = self.instantiate_trainer() def instantiate_trainer(self, **kwargs: Any) -> Trainer: """Instantiates the trainer. Args: kwargs: Any custom trainer arguments. """ extra_callbacks = [self._get(self.config_init, c) for c in self._parser(self.subcommand).callback_keys] trainer_config = {**self._get(self.config_init, "trainer", default={}), **kwargs} return self._instantiate_trainer(trainer_config, extra_callbacks) def _instantiate_trainer(self, config: Dict[str, Any], callbacks: List[Callback]) -> Trainer: key = "callbacks" if key in config: if config[key] is None: config[key] = [] elif not isinstance(config[key], list): config[key] = [config[key]] config[key].extend(callbacks) if key in self.trainer_defaults: value = self.trainer_defaults[key] config[key] += value if isinstance(value, list) else [value] if self.save_config_callback and not config.get("fast_dev_run", False): config_callback = self.save_config_callback( self._parser(self.subcommand), self.config.get(str(self.subcommand), self.config), **self.save_config_kwargs, ) config[key].append(config_callback) else: rank_zero_warn( f"The `{self.trainer_class.__qualname__}` class does not expose the `{key}` argument so they will" " not be included." ) return self.trainer_class(**config) def _parser(self, subcommand: Optional[str]) -> LightningArgumentParser: if subcommand is None: return self.parser # return the subcommand parser for the subcommand passed return self._subcommand_parsers[subcommand] def configure_optimizers( lightning_module: LightningModule, optimizer: Optimizer, lr_scheduler: Optional[LRSchedulerTypeUnion] = None ) -> Any: """Override to customize the :meth:`~lightning.pytorch.core.LightningModule.configure_optimizers` method. Args: lightning_module: A reference to the model. optimizer: The optimizer. lr_scheduler: The learning rate scheduler (if used). """ if lr_scheduler is None: return optimizer if isinstance(lr_scheduler, ReduceLROnPlateau): return { "optimizer": optimizer, "lr_scheduler": {"scheduler": lr_scheduler, "monitor": lr_scheduler.monitor}, } return [optimizer], [lr_scheduler] def _add_configure_optimizers_method_to_model(self, subcommand: Optional[str]) -> None: """Overrides the model's :meth:`~lightning.pytorch.core.LightningModule.configure_optimizers` method if a single optimizer and optionally a scheduler argument groups are added to the parser as 'AUTOMATIC'.""" if not self.auto_configure_optimizers: return parser = self._parser(subcommand) def get_automatic( class_type: Union[Type, Tuple[Type, ...]], register: Dict[str, Tuple[Union[Type, Tuple[Type, ...]], str]] ) -> List[str]: automatic = [] for key, (base_class, link_to) in register.items(): if not isinstance(base_class, tuple): base_class = (base_class,) if link_to == "AUTOMATIC" and any(issubclass(c, class_type) for c in base_class): automatic.append(key) return automatic optimizers = get_automatic(Optimizer, parser._optimizers) lr_schedulers = get_automatic(LRSchedulerTypeTuple, parser._lr_schedulers) if len(optimizers) == 0: return if len(optimizers) > 1 or len(lr_schedulers) > 1: raise MisconfigurationException( f"`{self.__class__.__name__}.add_configure_optimizers_method_to_model` expects at most one optimizer " f"and one lr_scheduler to be 'AUTOMATIC', but found {optimizers + lr_schedulers}. In this case the " "user is expected to link the argument groups and implement `configure_optimizers`, see " "https://lightning.ai/docs/pytorch/stable/common/lightning_cli.html" "#optimizers-and-learning-rate-schedulers" ) optimizer_class = parser._optimizers[optimizers[0]][0] optimizer_init = self._get(self.config_init, optimizers[0]) if not isinstance(optimizer_class, tuple): optimizer_init = _global_add_class_path(optimizer_class, optimizer_init) if not optimizer_init: # optimizers were registered automatically but not passed by the user return lr_scheduler_init = None if lr_schedulers: lr_scheduler_class = parser._lr_schedulers[lr_schedulers[0]][0] lr_scheduler_init = self._get(self.config_init, lr_schedulers[0]) if not isinstance(lr_scheduler_class, tuple): lr_scheduler_init = _global_add_class_path(lr_scheduler_class, lr_scheduler_init) if is_overridden("configure_optimizers", self.model): _warn( f"`{self.model.__class__.__name__}.configure_optimizers` will be overridden by " f"`{self.__class__.__name__}.configure_optimizers`." ) optimizer = instantiate_class(self.model.parameters(), optimizer_init) lr_scheduler = instantiate_class(optimizer, lr_scheduler_init) if lr_scheduler_init else None fn = partial(self.configure_optimizers, optimizer=optimizer, lr_scheduler=lr_scheduler) update_wrapper(fn, self.configure_optimizers) # necessary for `is_overridden` # override the existing method self.model.configure_optimizers = MethodType(fn, self.model) def _get(self, config: Namespace, key: str, default: Optional[Any] = None) -> Any: """Utility to get a config value which might be inside a subcommand.""" return config.get(str(self.subcommand), config).get(key, default) def _run_subcommand(self, subcommand: str) -> None: """Run the chosen subcommand.""" before_fn = getattr(self, f"before_{subcommand}", None) if callable(before_fn): before_fn() default = getattr(self.trainer, subcommand) fn = getattr(self, subcommand, default) fn_kwargs = self._prepare_subcommand_kwargs(subcommand) fn(**fn_kwargs) after_fn = getattr(self, f"after_{subcommand}", None) if callable(after_fn): after_fn() def _prepare_subcommand_kwargs(self, subcommand: str) -> Dict[str, Any]: """Prepares the keyword arguments to pass to the subcommand to run.""" fn_kwargs = { k: v for k, v in self.config_init[subcommand].items() if k in self._subcommand_method_arguments[subcommand] } fn_kwargs["model"] = self.model if self.datamodule is not None: fn_kwargs["datamodule"] = self.datamodule return fn_kwargs def _set_seed(self) -> None: """Sets the seed.""" config_seed = self._get(self.config, "seed_everything") if config_seed is False: return if config_seed is True: # user requested seeding, choose randomly config_seed = seed_everything(workers=True) else: config_seed = seed_everything(config_seed, workers=True) if self.subcommand: self.config[self.subcommand]["seed_everything"] = config_seed else: self.config["seed_everything"] = config_seed class PyTorchProfiler(Profiler): STEP_FUNCTIONS = {"training_step", "validation_step", "test_step", "predict_step"} AVAILABLE_SORT_KEYS = { "cpu_time", "cuda_time", "cpu_time_total", "cuda_time_total", "cpu_memory_usage", "cuda_memory_usage", "self_cpu_memory_usage", "self_cuda_memory_usage", "count", } def __init__( self, dirpath: Optional[Union[str, Path]] = None, filename: Optional[str] = None, group_by_input_shapes: bool = False, emit_nvtx: bool = False, export_to_chrome: bool = True, row_limit: int = 20, sort_by_key: Optional[str] = None, record_module_names: bool = True, table_kwargs: Optional[Dict[str, Any]] = None, **profiler_kwargs: Any, ) -> None: r"""This profiler uses PyTorch's Autograd Profiler and lets you inspect the cost of different operators inside your model - both on the CPU and GPU. Args: dirpath: Directory path for the ``filename``. If ``dirpath`` is ``None`` but ``filename`` is present, the ``trainer.log_dir`` (from :class:`~lightning.pytorch.loggers.tensorboard.TensorBoardLogger`) will be used. filename: If present, filename where the profiler results will be saved instead of printing to stdout. The ``.txt`` extension will be used automatically. group_by_input_shapes: Include operator input shapes and group calls by shape. emit_nvtx: Context manager that makes every autograd operation emit an NVTX range Run:: nvprof --profile-from-start off -o trace_name.prof -- <regular command here> To visualize, you can either use:: nvvp trace_name.prof torch.autograd.profiler.load_nvprof(path) export_to_chrome: Whether to export the sequence of profiled operators for Chrome. It will generate a ``.json`` file which can be read by Chrome. row_limit: Limit the number of rows in a table, ``-1`` is a special value that removes the limit completely. sort_by_key: Attribute used to sort entries. By default they are printed in the same order as they were registered. Valid keys include: ``cpu_time``, ``cuda_time``, ``cpu_time_total``, ``cuda_time_total``, ``cpu_memory_usage``, ``cuda_memory_usage``, ``self_cpu_memory_usage``, ``self_cuda_memory_usage``, ``count``. record_module_names: Whether to add module names while recording autograd operation. table_kwargs: Dictionary with keyword arguments for the summary table. \**profiler_kwargs: Keyword arguments for the PyTorch profiler. This depends on your PyTorch version Raises: MisconfigurationException: If arg ``sort_by_key`` is not present in ``AVAILABLE_SORT_KEYS``. If arg ``schedule`` is not a ``Callable``. If arg ``schedule`` does not return a ``torch.profiler.ProfilerAction``. """ super().__init__(dirpath=dirpath, filename=filename) self._group_by_input_shapes = group_by_input_shapes and profiler_kwargs.get("record_shapes", False) self._emit_nvtx = emit_nvtx self._export_to_chrome = export_to_chrome self._row_limit = row_limit self._sort_by_key = sort_by_key or f"{'cuda' if profiler_kwargs.get('use_cuda', False) else 'cpu'}_time_total" self._record_module_names = record_module_names self._profiler_kwargs = profiler_kwargs self._table_kwargs = table_kwargs if table_kwargs is not None else {} self.profiler: Optional[_PROFILER] = None self.function_events: Optional["EventList"] = None self._lightning_module: Optional["LightningModule"] = None # set by ProfilerConnector self._register: Optional[RegisterRecordFunction] = None self._parent_profiler: Optional[ContextManager] = None self._recording_map: Dict[str, record_function] = {} self._start_action_name: Optional[str] = None self._schedule: Optional[ScheduleWrapper] = None if _KINETO_AVAILABLE: self._init_kineto(profiler_kwargs) if self._sort_by_key not in self.AVAILABLE_SORT_KEYS: raise MisconfigurationException( f"Found sort_by_key: {self._sort_by_key}. Should be within {self.AVAILABLE_SORT_KEYS}. " ) for key in self._table_kwargs: if key in {"sort_by", "row_limit"}: raise KeyError( f"Found invalid table_kwargs key: {key}. This is already a positional argument of the Profiler." ) valid_table_keys = set(inspect.signature(EventList.table).parameters.keys()) - { "self", "sort_by", "row_limit", } if key not in valid_table_keys: raise KeyError(f"Found invalid table_kwargs key: {key}. Should be within {valid_table_keys}.") def _init_kineto(self, profiler_kwargs: Any) -> None: has_schedule = "schedule" in profiler_kwargs self._has_on_trace_ready = "on_trace_ready" in profiler_kwargs schedule = profiler_kwargs.get("schedule", None) if schedule is not None: if not callable(schedule): raise MisconfigurationException(f"Schedule should be a callable. Found: {schedule}") action = schedule(0) if not isinstance(action, ProfilerAction): raise MisconfigurationException( f"Schedule should return a `torch.profiler.ProfilerAction`. Found: {action}" ) self._default_schedule() schedule = schedule if has_schedule else self._default_schedule() self._schedule = ScheduleWrapper(schedule) if schedule is not None else schedule self._profiler_kwargs["schedule"] = self._schedule activities = profiler_kwargs.get("activities", None) self._profiler_kwargs["activities"] = activities or self._default_activities() self._export_to_flame_graph = profiler_kwargs.get("export_to_flame_graph", False) self._metric = profiler_kwargs.get("metric", "self_cpu_time_total") with_stack = profiler_kwargs.get("with_stack", False) or self._export_to_flame_graph self._profiler_kwargs["with_stack"] = with_stack def _total_steps(self) -> Union[int, float]: assert self._schedule is not None assert self._lightning_module is not None trainer = self._lightning_module.trainer if self._schedule.is_training: return trainer.num_training_batches if self._schedule.is_validating: num_val_batches = ( sum(trainer.num_val_batches) if isinstance(trainer.num_val_batches, list) else trainer.num_val_batches ) num_sanity_val_batches = ( sum(trainer.num_sanity_val_batches) if isinstance(trainer.num_sanity_val_batches, list) else trainer.num_sanity_val_batches ) return num_val_batches + num_sanity_val_batches if self._schedule.is_testing: num_test_batches = ( sum(trainer.num_test_batches) if isinstance(trainer.num_test_batches, list) else trainer.num_test_batches ) return num_test_batches if self._schedule.is_predicting: return sum(trainer.num_predict_batches) raise NotImplementedError("Unsupported schedule") def _should_override_schedule(self) -> bool: return ( self._lightning_module is not None and self._schedule is not None and self._total_steps < 5 and self._schedule._schedule == self._default_schedule() ) def _default_schedule() -> Optional[Callable]: if _KINETO_AVAILABLE: # Those schedule defaults allow the profiling overhead to be negligible over training time. return torch.profiler.schedule(wait=1, warmup=1, active=3) return None def _default_activities(self) -> List["ProfilerActivity"]: activities: List["ProfilerActivity"] = [] if not _KINETO_AVAILABLE: return activities if self._profiler_kwargs.get("use_cpu", True): activities.append(ProfilerActivity.CPU) if self._profiler_kwargs.get("use_cuda", is_cuda_available()): activities.append(ProfilerActivity.CUDA) return activities def start(self, action_name: str) -> None: if self.profiler is None: # close profiler if it is already opened. might happen if 2 profilers # are created and the first one did not call `describe` if torch.autograd._profiler_enabled(): torch.autograd._disable_profiler() if self._schedule is not None: self._schedule.setup(action_name) self._create_profilers() profiler = self.profiler.__enter__() if profiler is not None: self.profiler = profiler if self._parent_profiler is not None: self._parent_profiler.__enter__() if self._lightning_module is not None and self._register is None and self._record_module_names: self._register = RegisterRecordFunction(self._lightning_module) self._register.__enter__() if self.profiler is not None and action_name not in self._recording_map: # Add [pl][profile] in name for pytorch profiler to recognize recording = record_function("[pl][profile]" + action_name) recording.__enter__() self._recording_map[action_name] = recording def stop(self, action_name: str) -> None: if action_name in self._recording_map: self._recording_map[action_name].__exit__(None, None, None) del self._recording_map[action_name] if not _KINETO_AVAILABLE or self._emit_nvtx: return if self.profiler is not None and any(action_name.endswith(func) for func in self.STEP_FUNCTIONS): assert isinstance(self.profiler, torch.profiler.profile) if self._schedule is not None: self._schedule.pre_step(action_name) # the default schedule requires a minimum of 5 steps to properly work: `wait=1, warmup=1, active=3`. # otherwise, this will raise a `segmentation fault`. if self._should_override_schedule(): warning_cache.warn( "The PyTorch Profiler default schedule will be overridden as there is not enough " "steps to properly record traces." ) self._schedule = None self.profiler.schedule = torch.profiler.profiler._default_schedule_fn def on_trace_ready(profiler: _PROFILER) -> None: if self.dirpath is not None: if self._export_to_chrome: handler = tensorboard_trace_handler( str(self.dirpath), self._prepare_filename(action_name=action_name, extension="") ) handler(profiler) if self._export_to_flame_graph: path = os.path.join( self.dirpath, self._prepare_filename(action_name=action_name, extension=".stack") ) assert isinstance(profiler, torch.autograd.profiler.profile) profiler.export_stacks(path, metric=self._metric) else: rank_zero_warn("The PyTorchProfiler failed to export trace as `dirpath` is None") if not self._has_on_trace_ready: self.profiler.on_trace_ready = on_trace_ready if self._schedule is not None: self.profiler.step_num = self._schedule.num_step self.profiler.step() self.profiler.add_metadata("Framework", "pytorch-lightning") def summary(self) -> str: if not self._profiler_kwargs.get("enabled", True) or self._emit_nvtx: return "" self._delete_profilers() if not self.function_events: return "" if self._export_to_chrome and not _KINETO_AVAILABLE: filename = f"{self.local_rank}_trace.json" path_to_trace = filename if self.dirpath is None else os.path.join(self.dirpath, filename) self.function_events.export_chrome_trace(path_to_trace) data = self.function_events.key_averages(group_by_input_shapes=self._group_by_input_shapes) table = data.table(sort_by=self._sort_by_key, row_limit=self._row_limit, **self._table_kwargs) recorded_stats = {"records": table} return self._stats_to_str(recorded_stats) def _create_profilers(self) -> None: if self.profiler is not None: return if self._emit_nvtx: if self._parent_profiler is None: self._parent_profiler = torch.cuda.profiler.profile() self.profiler = self._create_profiler(torch.autograd.profiler.emit_nvtx) else: self._parent_profiler = None self.profiler = self._create_profiler( torch.profiler.profile if _KINETO_AVAILABLE else torch.autograd.profiler.profile ) def _create_profiler(self, profiler: Type[_PROFILER]) -> _PROFILER: init_parameters = inspect.signature(profiler.__init__).parameters kwargs = {k: v for k, v in self._profiler_kwargs.items() if k in init_parameters} return profiler(**kwargs) def _cache_functions_events(self) -> None: if self._emit_nvtx: return if _KINETO_AVAILABLE: assert isinstance(self.profiler, torch.profiler.profile) self.function_events = self.profiler.events() else: assert isinstance(self.profiler, torch.autograd.profiler.profile) self.function_events = self.profiler.function_events def _delete_profilers(self) -> None: if self.profiler is not None: self.profiler.__exit__(None, None, None) self._cache_functions_events() self.profiler = None if self._schedule is not None: self._schedule.reset() if self._parent_profiler is not None: self._parent_profiler.__exit__(None, None, None) self._parent_profiler = None if self._register is not None: self._register.__exit__(None, None, None) self._register = None def teardown(self, stage: Optional[str]) -> None: self._delete_profilers() for k in list(self._recording_map): self.stop(k) self._recording_map = {} super().teardown(stage=stage) def cli_main(): cli = LightningCLI( ModelToProfile, CIFAR10DataModule, save_config_kwargs={"overwrite": True}, trainer_defaults={ "profiler": PyTorchProfiler(), "max_epochs": 1, "limit_train_batches": 15, "limit_val_batches": 15, "accelerator": "gpu", }, run=False, ) cli.trainer.fit(cli.model, datamodule=cli.datamodule)
null
155,722
from os import path from typing import Optional, Tuple import torch import torch.nn.functional as F from lightning.pytorch import LightningDataModule, LightningModule, Trainer, callbacks, cli_lightning_logo from lightning.pytorch.cli import LightningCLI from lightning.pytorch.demos.mnist_datamodule import MNIST from lightning.pytorch.utilities import rank_zero_only from lightning.pytorch.utilities.imports import _TORCHVISION_AVAILABLE from torch import nn from torch.utils.data import DataLoader, random_split class ImageSampler(callbacks.Callback): def __init__( self, num_samples: int = 3, nrow: int = 8, padding: int = 2, normalize: bool = True, value_range: Optional[Tuple[int, int]] = None, scale_each: bool = False, pad_value: int = 0, ) -> None: """ Args: num_samples: Number of images displayed in the grid. Default: ``3``. nrow: Number of images displayed in each row of the grid. The final grid size is ``(B / nrow, nrow)``. Default: ``8``. padding: Amount of padding. Default: ``2``. normalize: If ``True``, shift the image to the range (0, 1), by the min and max values specified by :attr:`range`. Default: ``False``. value_range: Tuple (min, max) where min and max are numbers, then these numbers are used to normalize the image. By default, min and max are computed from the tensor. scale_each: If ``True``, scale each image in the batch of images separately rather than the (min, max) over all images. Default: ``False``. pad_value: Value for the padded pixels. Default: ``0``. """ if not _TORCHVISION_AVAILABLE: # pragma: no cover raise ModuleNotFoundError("You want to use `torchvision` which is not installed yet.") super().__init__() self.num_samples = num_samples self.nrow = nrow self.padding = padding self.normalize = normalize self.value_range = value_range self.scale_each = scale_each self.pad_value = pad_value def _to_grid(self, images): return torchvision.utils.make_grid( tensor=images, nrow=self.nrow, padding=self.padding, normalize=self.normalize, value_range=self.value_range, scale_each=self.scale_each, pad_value=self.pad_value, ) def on_train_epoch_end(self, trainer: Trainer, pl_module: LightningModule) -> None: if not _TORCHVISION_AVAILABLE: return images, _ = next(iter(DataLoader(trainer.datamodule.mnist_val, batch_size=self.num_samples))) images_flattened = images.view(images.size(0), -1) # generate images with torch.no_grad(): pl_module.eval() images_generated = pl_module(images_flattened.to(pl_module.device)) pl_module.train() if trainer.current_epoch == 0: save_image(self._to_grid(images), f"grid_ori_{trainer.current_epoch}.png") save_image(self._to_grid(images_generated.reshape(images.shape)), f"grid_generated_{trainer.current_epoch}.png") class LitAutoEncoder(LightningModule): """ >>> LitAutoEncoder() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE LitAutoEncoder( (encoder): ... (decoder): ... ) """ def __init__(self, hidden_dim: int = 64, learning_rate=10e-3): super().__init__() self.save_hyperparameters() self.encoder = nn.Sequential(nn.Linear(28 * 28, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, 3)) self.decoder = nn.Sequential(nn.Linear(3, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, 28 * 28)) def forward(self, x): z = self.encoder(x) return self.decoder(z) def training_step(self, batch, batch_idx): return self._common_step(batch, batch_idx, "train") def validation_step(self, batch, batch_idx): self._common_step(batch, batch_idx, "val") def test_step(self, batch, batch_idx): self._common_step(batch, batch_idx, "test") def predict_step(self, batch, batch_idx, dataloader_idx=None): x = self._prepare_batch(batch) return self(x) def configure_optimizers(self): return torch.optim.Adam(self.parameters(), lr=self.hparams.learning_rate) def _prepare_batch(self, batch): x, _ = batch return x.view(x.size(0), -1) def _common_step(self, batch, batch_idx, stage: str): x = self._prepare_batch(batch) loss = F.mse_loss(x, self(x)) self.log(f"{stage}_loss", loss, on_step=True) return loss class MyDataModule(LightningDataModule): def __init__(self, batch_size: int = 32): super().__init__() dataset = MNIST(DATASETS_PATH, train=True, download=True, transform=transforms.ToTensor()) self.mnist_test = MNIST(DATASETS_PATH, train=False, download=True, transform=transforms.ToTensor()) self.mnist_train, self.mnist_val = random_split( dataset, [55000, 5000], generator=torch.Generator().manual_seed(42) ) self.batch_size = batch_size def train_dataloader(self): return DataLoader(self.mnist_train, batch_size=self.batch_size) def val_dataloader(self): return DataLoader(self.mnist_val, batch_size=self.batch_size) def test_dataloader(self): return DataLoader(self.mnist_test, batch_size=self.batch_size) def predict_dataloader(self): return DataLoader(self.mnist_test, batch_size=self.batch_size) class LightningCLI: """Implementation of a configurable command line tool for pytorch-lightning.""" def __init__( self, model_class: Optional[Union[Type[LightningModule], Callable[..., LightningModule]]] = None, datamodule_class: Optional[Union[Type[LightningDataModule], Callable[..., LightningDataModule]]] = None, save_config_callback: Optional[Type[SaveConfigCallback]] = SaveConfigCallback, save_config_kwargs: Optional[Dict[str, Any]] = None, trainer_class: Union[Type[Trainer], Callable[..., Trainer]] = Trainer, trainer_defaults: Optional[Dict[str, Any]] = None, seed_everything_default: Union[bool, int] = True, parser_kwargs: Optional[Union[Dict[str, Any], Dict[str, Dict[str, Any]]]] = None, subclass_mode_model: bool = False, subclass_mode_data: bool = False, args: ArgsType = None, run: bool = True, auto_configure_optimizers: bool = True, ) -> None: """Receives as input pytorch-lightning classes (or callables which return pytorch-lightning classes), which are called / instantiated using a parsed configuration file and / or command line args. Parsing of configuration from environment variables can be enabled by setting ``parser_kwargs={"default_env": True}``. A full configuration yaml would be parsed from ``PL_CONFIG`` if set. Individual settings are so parsed from variables named for example ``PL_TRAINER__MAX_EPOCHS``. For more info, read :ref:`the CLI docs <lightning-cli>`. Args: model_class: An optional :class:`~lightning.pytorch.core.LightningModule` class to train on or a callable which returns a :class:`~lightning.pytorch.core.LightningModule` instance when called. If ``None``, you can pass a registered model with ``--model=MyModel``. datamodule_class: An optional :class:`~lightning.pytorch.core.datamodule.LightningDataModule` class or a callable which returns a :class:`~lightning.pytorch.core.datamodule.LightningDataModule` instance when called. If ``None``, you can pass a registered datamodule with ``--data=MyDataModule``. save_config_callback: A callback class to save the config. save_config_kwargs: Parameters that will be used to instantiate the save_config_callback. trainer_class: An optional subclass of the :class:`~lightning.pytorch.trainer.trainer.Trainer` class or a callable which returns a :class:`~lightning.pytorch.trainer.trainer.Trainer` instance when called. trainer_defaults: Set to override Trainer defaults or add persistent callbacks. The callbacks added through this argument will not be configurable from a configuration file and will always be present for this particular CLI. Alternatively, configurable callbacks can be added as explained in :ref:`the CLI docs <lightning-cli>`. seed_everything_default: Number for the :func:`~lightning.fabric.utilities.seed.seed_everything` seed value. Set to True to automatically choose a seed value. Setting it to False will avoid calling ``seed_everything``. parser_kwargs: Additional arguments to instantiate each ``LightningArgumentParser``. subclass_mode_model: Whether model can be any `subclass <https://jsonargparse.readthedocs.io/en/stable/#class-type-and-sub-classes>`_ of the given class. subclass_mode_data: Whether datamodule can be any `subclass <https://jsonargparse.readthedocs.io/en/stable/#class-type-and-sub-classes>`_ of the given class. args: Arguments to parse. If ``None`` the arguments are taken from ``sys.argv``. Command line style arguments can be given in a ``list``. Alternatively, structured config options can be given in a ``dict`` or ``jsonargparse.Namespace``. run: Whether subcommands should be added to run a :class:`~lightning.pytorch.trainer.trainer.Trainer` method. If set to ``False``, the trainer and model classes will be instantiated only. """ self.save_config_callback = save_config_callback self.save_config_kwargs = save_config_kwargs or {} self.trainer_class = trainer_class self.trainer_defaults = trainer_defaults or {} self.seed_everything_default = seed_everything_default self.parser_kwargs = parser_kwargs or {} self.auto_configure_optimizers = auto_configure_optimizers self.model_class = model_class # used to differentiate between the original value and the processed value self._model_class = model_class or LightningModule self.subclass_mode_model = (model_class is None) or subclass_mode_model self.datamodule_class = datamodule_class # used to differentiate between the original value and the processed value self._datamodule_class = datamodule_class or LightningDataModule self.subclass_mode_data = (datamodule_class is None) or subclass_mode_data main_kwargs, subparser_kwargs = self._setup_parser_kwargs(self.parser_kwargs) self.setup_parser(run, main_kwargs, subparser_kwargs) self.parse_arguments(self.parser, args) self.subcommand = self.config["subcommand"] if run else None self._set_seed() self._add_instantiators() self.before_instantiate_classes() self.instantiate_classes() if self.subcommand is not None: self._run_subcommand(self.subcommand) def _setup_parser_kwargs(self, parser_kwargs: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]: subcommand_names = self.subcommands().keys() main_kwargs = {k: v for k, v in parser_kwargs.items() if k not in subcommand_names} subparser_kwargs = {k: v for k, v in parser_kwargs.items() if k in subcommand_names} return main_kwargs, subparser_kwargs def init_parser(self, **kwargs: Any) -> LightningArgumentParser: """Method that instantiates the argument parser.""" kwargs.setdefault("dump_header", [f"lightning.pytorch=={pl.__version__}"]) parser = LightningArgumentParser(**kwargs) parser.add_argument( "-c", "--config", action=ActionConfigFile, help="Path to a configuration file in json or yaml format." ) return parser def setup_parser( self, add_subcommands: bool, main_kwargs: Dict[str, Any], subparser_kwargs: Dict[str, Any] ) -> None: """Initialize and setup the parser, subcommands, and arguments.""" self.parser = self.init_parser(**main_kwargs) if add_subcommands: self._subcommand_method_arguments: Dict[str, List[str]] = {} self._add_subcommands(self.parser, **subparser_kwargs) else: self._add_arguments(self.parser) def add_default_arguments_to_parser(self, parser: LightningArgumentParser) -> None: """Adds default arguments to the parser.""" parser.add_argument( "--seed_everything", type=Union[bool, int], default=self.seed_everything_default, help=( "Set to an int to run seed_everything with this value before classes instantiation." "Set to True to use a random seed." ), ) def add_core_arguments_to_parser(self, parser: LightningArgumentParser) -> None: """Adds arguments from the core classes to the parser.""" parser.add_lightning_class_args(self.trainer_class, "trainer") trainer_defaults = {"trainer." + k: v for k, v in self.trainer_defaults.items() if k != "callbacks"} parser.set_defaults(trainer_defaults) parser.add_lightning_class_args(self._model_class, "model", subclass_mode=self.subclass_mode_model) if self.datamodule_class is not None: parser.add_lightning_class_args(self._datamodule_class, "data", subclass_mode=self.subclass_mode_data) else: # this should not be required because the user might want to use the `LightningModule` dataloaders parser.add_lightning_class_args( self._datamodule_class, "data", subclass_mode=self.subclass_mode_data, required=False ) def _add_arguments(self, parser: LightningArgumentParser) -> None: # default + core + custom arguments self.add_default_arguments_to_parser(parser) self.add_core_arguments_to_parser(parser) self.add_arguments_to_parser(parser) # add default optimizer args if necessary if self.auto_configure_optimizers: if not parser._optimizers: # already added by the user in `add_arguments_to_parser` parser.add_optimizer_args((Optimizer,)) if not parser._lr_schedulers: # already added by the user in `add_arguments_to_parser` parser.add_lr_scheduler_args(LRSchedulerTypeTuple) self.link_optimizers_and_lr_schedulers(parser) def add_arguments_to_parser(self, parser: LightningArgumentParser) -> None: """Implement to add extra arguments to the parser or link arguments. Args: parser: The parser object to which arguments can be added """ def subcommands() -> Dict[str, Set[str]]: """Defines the list of available subcommands and the arguments to skip.""" return { "fit": {"model", "train_dataloaders", "val_dataloaders", "datamodule"}, "validate": {"model", "dataloaders", "datamodule"}, "test": {"model", "dataloaders", "datamodule"}, "predict": {"model", "dataloaders", "datamodule"}, } def _add_subcommands(self, parser: LightningArgumentParser, **kwargs: Any) -> None: """Adds subcommands to the input parser.""" self._subcommand_parsers: Dict[str, LightningArgumentParser] = {} parser_subcommands = parser.add_subcommands() # the user might have passed a builder function trainer_class = ( self.trainer_class if isinstance(self.trainer_class, type) else class_from_function(self.trainer_class) ) # register all subcommands in separate subcommand parsers under the main parser for subcommand in self.subcommands(): fn = getattr(trainer_class, subcommand) # extract the first line description in the docstring for the subcommand help message description = _get_short_description(fn) subparser_kwargs = kwargs.get(subcommand, {}) subparser_kwargs.setdefault("description", description) subcommand_parser = self._prepare_subcommand_parser(trainer_class, subcommand, **subparser_kwargs) self._subcommand_parsers[subcommand] = subcommand_parser parser_subcommands.add_subcommand(subcommand, subcommand_parser, help=description) def _prepare_subcommand_parser(self, klass: Type, subcommand: str, **kwargs: Any) -> LightningArgumentParser: parser = self.init_parser(**kwargs) self._add_arguments(parser) # subcommand arguments skip: Set[Union[str, int]] = set(self.subcommands()[subcommand]) added = parser.add_method_arguments(klass, subcommand, skip=skip) # need to save which arguments were added to pass them to the method later self._subcommand_method_arguments[subcommand] = added return parser def link_optimizers_and_lr_schedulers(parser: LightningArgumentParser) -> None: """Creates argument links for optimizers and learning rate schedulers that specified a ``link_to``.""" optimizers_and_lr_schedulers = {**parser._optimizers, **parser._lr_schedulers} for key, (class_type, link_to) in optimizers_and_lr_schedulers.items(): if link_to == "AUTOMATIC": continue if isinstance(class_type, tuple): parser.link_arguments(key, link_to) else: add_class_path = _add_class_path_generator(class_type) parser.link_arguments(key, link_to, compute_fn=add_class_path) def parse_arguments(self, parser: LightningArgumentParser, args: ArgsType) -> None: """Parses command line arguments and stores it in ``self.config``.""" if args is not None and len(sys.argv) > 1: rank_zero_warn( "LightningCLI's args parameter is intended to run from within Python like if it were from the command " "line. To prevent mistakes it is not recommended to provide both args and command line arguments, got: " f"sys.argv[1:]={sys.argv[1:]}, args={args}." ) if isinstance(args, (dict, Namespace)): self.config = parser.parse_object(args) else: self.config = parser.parse_args(args) def _add_instantiators(self) -> None: self.config_dump = yaml.safe_load(self.parser.dump(self.config, skip_link_targets=False)) if "subcommand" in self.config: self.config_dump = self.config_dump[self.config.subcommand] self.parser.add_instantiator( _InstantiatorFn(cli=self, key="model"), _get_module_type(self._model_class), subclasses=self.subclass_mode_model, ) self.parser.add_instantiator( _InstantiatorFn(cli=self, key="data"), _get_module_type(self._datamodule_class), subclasses=self.subclass_mode_data, ) def before_instantiate_classes(self) -> None: """Implement to run some code before instantiating the classes.""" def instantiate_classes(self) -> None: """Instantiates the classes and sets their attributes.""" self.config_init = self.parser.instantiate_classes(self.config) self.datamodule = self._get(self.config_init, "data") self.model = self._get(self.config_init, "model") self._add_configure_optimizers_method_to_model(self.subcommand) self.trainer = self.instantiate_trainer() def instantiate_trainer(self, **kwargs: Any) -> Trainer: """Instantiates the trainer. Args: kwargs: Any custom trainer arguments. """ extra_callbacks = [self._get(self.config_init, c) for c in self._parser(self.subcommand).callback_keys] trainer_config = {**self._get(self.config_init, "trainer", default={}), **kwargs} return self._instantiate_trainer(trainer_config, extra_callbacks) def _instantiate_trainer(self, config: Dict[str, Any], callbacks: List[Callback]) -> Trainer: key = "callbacks" if key in config: if config[key] is None: config[key] = [] elif not isinstance(config[key], list): config[key] = [config[key]] config[key].extend(callbacks) if key in self.trainer_defaults: value = self.trainer_defaults[key] config[key] += value if isinstance(value, list) else [value] if self.save_config_callback and not config.get("fast_dev_run", False): config_callback = self.save_config_callback( self._parser(self.subcommand), self.config.get(str(self.subcommand), self.config), **self.save_config_kwargs, ) config[key].append(config_callback) else: rank_zero_warn( f"The `{self.trainer_class.__qualname__}` class does not expose the `{key}` argument so they will" " not be included." ) return self.trainer_class(**config) def _parser(self, subcommand: Optional[str]) -> LightningArgumentParser: if subcommand is None: return self.parser # return the subcommand parser for the subcommand passed return self._subcommand_parsers[subcommand] def configure_optimizers( lightning_module: LightningModule, optimizer: Optimizer, lr_scheduler: Optional[LRSchedulerTypeUnion] = None ) -> Any: """Override to customize the :meth:`~lightning.pytorch.core.LightningModule.configure_optimizers` method. Args: lightning_module: A reference to the model. optimizer: The optimizer. lr_scheduler: The learning rate scheduler (if used). """ if lr_scheduler is None: return optimizer if isinstance(lr_scheduler, ReduceLROnPlateau): return { "optimizer": optimizer, "lr_scheduler": {"scheduler": lr_scheduler, "monitor": lr_scheduler.monitor}, } return [optimizer], [lr_scheduler] def _add_configure_optimizers_method_to_model(self, subcommand: Optional[str]) -> None: """Overrides the model's :meth:`~lightning.pytorch.core.LightningModule.configure_optimizers` method if a single optimizer and optionally a scheduler argument groups are added to the parser as 'AUTOMATIC'.""" if not self.auto_configure_optimizers: return parser = self._parser(subcommand) def get_automatic( class_type: Union[Type, Tuple[Type, ...]], register: Dict[str, Tuple[Union[Type, Tuple[Type, ...]], str]] ) -> List[str]: automatic = [] for key, (base_class, link_to) in register.items(): if not isinstance(base_class, tuple): base_class = (base_class,) if link_to == "AUTOMATIC" and any(issubclass(c, class_type) for c in base_class): automatic.append(key) return automatic optimizers = get_automatic(Optimizer, parser._optimizers) lr_schedulers = get_automatic(LRSchedulerTypeTuple, parser._lr_schedulers) if len(optimizers) == 0: return if len(optimizers) > 1 or len(lr_schedulers) > 1: raise MisconfigurationException( f"`{self.__class__.__name__}.add_configure_optimizers_method_to_model` expects at most one optimizer " f"and one lr_scheduler to be 'AUTOMATIC', but found {optimizers + lr_schedulers}. In this case the " "user is expected to link the argument groups and implement `configure_optimizers`, see " "https://lightning.ai/docs/pytorch/stable/common/lightning_cli.html" "#optimizers-and-learning-rate-schedulers" ) optimizer_class = parser._optimizers[optimizers[0]][0] optimizer_init = self._get(self.config_init, optimizers[0]) if not isinstance(optimizer_class, tuple): optimizer_init = _global_add_class_path(optimizer_class, optimizer_init) if not optimizer_init: # optimizers were registered automatically but not passed by the user return lr_scheduler_init = None if lr_schedulers: lr_scheduler_class = parser._lr_schedulers[lr_schedulers[0]][0] lr_scheduler_init = self._get(self.config_init, lr_schedulers[0]) if not isinstance(lr_scheduler_class, tuple): lr_scheduler_init = _global_add_class_path(lr_scheduler_class, lr_scheduler_init) if is_overridden("configure_optimizers", self.model): _warn( f"`{self.model.__class__.__name__}.configure_optimizers` will be overridden by " f"`{self.__class__.__name__}.configure_optimizers`." ) optimizer = instantiate_class(self.model.parameters(), optimizer_init) lr_scheduler = instantiate_class(optimizer, lr_scheduler_init) if lr_scheduler_init else None fn = partial(self.configure_optimizers, optimizer=optimizer, lr_scheduler=lr_scheduler) update_wrapper(fn, self.configure_optimizers) # necessary for `is_overridden` # override the existing method self.model.configure_optimizers = MethodType(fn, self.model) def _get(self, config: Namespace, key: str, default: Optional[Any] = None) -> Any: """Utility to get a config value which might be inside a subcommand.""" return config.get(str(self.subcommand), config).get(key, default) def _run_subcommand(self, subcommand: str) -> None: """Run the chosen subcommand.""" before_fn = getattr(self, f"before_{subcommand}", None) if callable(before_fn): before_fn() default = getattr(self.trainer, subcommand) fn = getattr(self, subcommand, default) fn_kwargs = self._prepare_subcommand_kwargs(subcommand) fn(**fn_kwargs) after_fn = getattr(self, f"after_{subcommand}", None) if callable(after_fn): after_fn() def _prepare_subcommand_kwargs(self, subcommand: str) -> Dict[str, Any]: """Prepares the keyword arguments to pass to the subcommand to run.""" fn_kwargs = { k: v for k, v in self.config_init[subcommand].items() if k in self._subcommand_method_arguments[subcommand] } fn_kwargs["model"] = self.model if self.datamodule is not None: fn_kwargs["datamodule"] = self.datamodule return fn_kwargs def _set_seed(self) -> None: """Sets the seed.""" config_seed = self._get(self.config, "seed_everything") if config_seed is False: return if config_seed is True: # user requested seeding, choose randomly config_seed = seed_everything(workers=True) else: config_seed = seed_everything(config_seed, workers=True) if self.subcommand: self.config[self.subcommand]["seed_everything"] = config_seed else: self.config["seed_everything"] = config_seed def cli_main(): cli = LightningCLI( LitAutoEncoder, MyDataModule, seed_everything_default=1234, run=False, # used to de-activate automatic fitting. trainer_defaults={"callbacks": ImageSampler(), "max_epochs": 10}, save_config_kwargs={"overwrite": True}, ) cli.trainer.fit(cli.model, datamodule=cli.datamodule) cli.trainer.test(ckpt_path="best", datamodule=cli.datamodule) predictions = cli.trainer.predict(ckpt_path="best", datamodule=cli.datamodule) print(predictions[0])
null
155,723
from os import path from typing import Optional import torch from lightning.pytorch import LightningDataModule, LightningModule, cli_lightning_logo from lightning.pytorch.cli import LightningCLI from lightning.pytorch.demos.mnist_datamodule import MNIST from lightning.pytorch.utilities.imports import _TORCHVISION_AVAILABLE from torch.nn import functional as F from torch.utils.data import DataLoader, random_split class LitClassifier(LightningModule): def __init__(self, backbone: Optional[Backbone] = None, learning_rate: float = 0.0001): def forward(self, x): def training_step(self, batch, batch_idx): def validation_step(self, batch, batch_idx): def test_step(self, batch, batch_idx): def predict_step(self, batch, batch_idx, dataloader_idx=None): def configure_optimizers(self): class MyDataModule(LightningDataModule): def __init__(self, batch_size: int = 32): def train_dataloader(self): def val_dataloader(self): def test_dataloader(self): def predict_dataloader(self): class LightningCLI: def __init__( self, model_class: Optional[Union[Type[LightningModule], Callable[..., LightningModule]]] = None, datamodule_class: Optional[Union[Type[LightningDataModule], Callable[..., LightningDataModule]]] = None, save_config_callback: Optional[Type[SaveConfigCallback]] = SaveConfigCallback, save_config_kwargs: Optional[Dict[str, Any]] = None, trainer_class: Union[Type[Trainer], Callable[..., Trainer]] = Trainer, trainer_defaults: Optional[Dict[str, Any]] = None, seed_everything_default: Union[bool, int] = True, parser_kwargs: Optional[Union[Dict[str, Any], Dict[str, Dict[str, Any]]]] = None, subclass_mode_model: bool = False, subclass_mode_data: bool = False, args: ArgsType = None, run: bool = True, auto_configure_optimizers: bool = True, ) -> None: def _setup_parser_kwargs(self, parser_kwargs: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]: def init_parser(self, **kwargs: Any) -> LightningArgumentParser: def setup_parser( self, add_subcommands: bool, main_kwargs: Dict[str, Any], subparser_kwargs: Dict[str, Any] ) -> None: def add_default_arguments_to_parser(self, parser: LightningArgumentParser) -> None: def add_core_arguments_to_parser(self, parser: LightningArgumentParser) -> None: def _add_arguments(self, parser: LightningArgumentParser) -> None: def add_arguments_to_parser(self, parser: LightningArgumentParser) -> None: def subcommands() -> Dict[str, Set[str]]: def _add_subcommands(self, parser: LightningArgumentParser, **kwargs: Any) -> None: def _prepare_subcommand_parser(self, klass: Type, subcommand: str, **kwargs: Any) -> LightningArgumentParser: def link_optimizers_and_lr_schedulers(parser: LightningArgumentParser) -> None: def parse_arguments(self, parser: LightningArgumentParser, args: ArgsType) -> None: def _add_instantiators(self) -> None: def before_instantiate_classes(self) -> None: def instantiate_classes(self) -> None: def instantiate_trainer(self, **kwargs: Any) -> Trainer: def _instantiate_trainer(self, config: Dict[str, Any], callbacks: List[Callback]) -> Trainer: def _parser(self, subcommand: Optional[str]) -> LightningArgumentParser: def configure_optimizers( lightning_module: LightningModule, optimizer: Optimizer, lr_scheduler: Optional[LRSchedulerTypeUnion] = None ) -> Any: def _add_configure_optimizers_method_to_model(self, subcommand: Optional[str]) -> None: def get_automatic( class_type: Union[Type, Tuple[Type, ...]], register: Dict[str, Tuple[Union[Type, Tuple[Type, ...]], str]] ) -> List[str]: def _get(self, config: Namespace, key: str, default: Optional[Any] = None) -> Any: def _run_subcommand(self, subcommand: str) -> None: def _prepare_subcommand_kwargs(self, subcommand: str) -> Dict[str, Any]: def _set_seed(self) -> None: def cli_main(): cli = LightningCLI( LitClassifier, MyDataModule, seed_everything_default=1234, save_config_kwargs={"overwrite": True}, run=False ) cli.trainer.fit(cli.model, datamodule=cli.datamodule) cli.trainer.test(ckpt_path="best", datamodule=cli.datamodule) predictions = cli.trainer.predict(ckpt_path="best", datamodule=cli.datamodule) print(predictions[0])
null
155,724
import argparse from typing import Callable, Iterator, List, Tuple import gym import torch from lightning.pytorch import LightningModule, Trainer, cli_lightning_logo, seed_everything from torch import nn from torch.distributions import Categorical, Normal from torch.optim.optimizer import Optimizer from torch.utils.data import DataLoader, IterableDataset The provided code snippet includes necessary dependencies for implementing the `create_mlp` function. Write a Python function `def create_mlp(input_shape: Tuple[int], n_actions: int, hidden_size: int = 128)` to solve the following problem: Simple Multi-Layer Perceptron network. Here is the function: def create_mlp(input_shape: Tuple[int], n_actions: int, hidden_size: int = 128): """Simple Multi-Layer Perceptron network.""" return nn.Sequential( nn.Linear(input_shape[0], hidden_size), nn.ReLU(), nn.Linear(hidden_size, hidden_size), nn.ReLU(), nn.Linear(hidden_size, n_actions), )
Simple Multi-Layer Perceptron network.
155,725
import logging from pathlib import Path from typing import Union import torch import torch.nn.functional as F from lightning.pytorch import LightningDataModule, LightningModule, cli_lightning_logo from lightning.pytorch.callbacks.finetuning import BaseFinetuning from lightning.pytorch.cli import LightningCLI from lightning.pytorch.utilities import rank_zero_info from lightning.pytorch.utilities.model_helpers import get_torchvision_model from torch import nn, optim from torch.optim.lr_scheduler import MultiStepLR from torch.optim.optimizer import Optimizer from torch.utils.data import DataLoader from torchmetrics import Accuracy from torchvision import transforms from torchvision.datasets import ImageFolder from torchvision.datasets.utils import download_and_extract_archive class CatDogImageDataModule(LightningDataModule): def __init__(self, dl_path: Union[str, Path] = "data", num_workers: int = 0, batch_size: int = 8): def prepare_data(self): def data_path(self): def normalize_transform(self): def train_transform(self): def valid_transform(self): def create_dataset(self, root, transform): def __dataloader(self, train: bool): def train_dataloader(self): def val_dataloader(self): class TransferLearningModel(LightningModule): def __init__( self, backbone: str = "resnet50", train_bn: bool = False, milestones: tuple = (2, 4), batch_size: int = 32, lr: float = 1e-3, lr_scheduler_gamma: float = 1e-1, num_workers: int = 6, **kwargs, ) -> None: def __build_model(self): def forward(self, x): def loss(self, logits, labels): def training_step(self, batch, batch_idx): def validation_step(self, batch, batch_idx): def configure_optimizers(self): class MyLightningCLI(LightningCLI): def add_arguments_to_parser(self, parser): def cli_main(): MyLightningCLI(TransferLearningModel, CatDogImageDataModule, seed_everything_default=1234)
null
155,726
import os import random from argparse import ArgumentParser, Namespace import numpy as np import torch import torch.nn.functional as F import torchvision.transforms as transforms from lightning.pytorch import LightningModule, Trainer, cli_lightning_logo from PIL import Image from torch import nn from torch.utils.data import DataLoader, Dataset class KITTI(Dataset): """Class for KITTI Semantic Segmentation Benchmark dataset. Dataset link - http://www.cvlibs.net/datasets/kitti/eval_semseg.php?benchmark=semantics2015 There are 34 classes in the given labels. However, not all of them are useful for training (like railings on highways, road dividers, etc.). So, these useless classes (the pixel values of these classes) are stored in the `void_labels`. The useful classes are stored in the `valid_labels`. The `encode_segmap` function sets all pixels with any of the `void_labels` to `ignore_index` (250 by default). It also sets all of the valid pixels to the appropriate value between 0 and `len(valid_labels)` (since that is the number of valid classes), so it can be used properly by the loss function when comparing with the output. The `get_filenames` function retrieves the filenames of all images in the given `path` and saves the absolute path in a list. In the `get_item` function, images and masks are resized to the given `img_size`, masks are encoded using `encode_segmap`, and given `transform` (if any) are applied to the image only (mask does not usually require transforms, but they can be implemented in a similar way). """ IMAGE_PATH = os.path.join("training", "image_2") MASK_PATH = os.path.join("training", "semantic") def __init__( self, data_path: str, split: str, img_size: tuple = (1242, 376), void_labels: list = DEFAULT_VOID_LABELS, valid_labels: list = DEFAULT_VALID_LABELS, transform=None, ): self.img_size = img_size self.void_labels = void_labels self.valid_labels = valid_labels self.ignore_index = 250 self.class_map = dict(zip(self.valid_labels, range(len(self.valid_labels)))) self.transform = transform self.split = split self.data_path = data_path self.img_path = os.path.join(self.data_path, self.IMAGE_PATH) self.mask_path = os.path.join(self.data_path, self.MASK_PATH) self.img_list = self.get_filenames(self.img_path) self.mask_list = self.get_filenames(self.mask_path) # Split between train and valid set (80/20) random_inst = random.Random(12345) # for repeatability n_items = len(self.img_list) idxs = random_inst.sample(range(n_items), n_items // 5) if self.split == "train": idxs = [idx for idx in range(n_items) if idx not in idxs] self.img_list = [self.img_list[i] for i in idxs] self.mask_list = [self.mask_list[i] for i in idxs] def __len__(self): return len(self.img_list) def __getitem__(self, idx): img = Image.open(self.img_list[idx]) img = img.resize(self.img_size) img = np.array(img) mask = Image.open(self.mask_list[idx]).convert("L") mask = mask.resize(self.img_size) mask = np.array(mask) mask = self.encode_segmap(mask) if self.transform: img = self.transform(img) return img, mask def encode_segmap(self, mask): """Sets void classes to zero so they won't be considered for training.""" for voidc in self.void_labels: mask[mask == voidc] = self.ignore_index for validc in self.valid_labels: mask[mask == validc] = self.class_map[validc] # remove extra idxs from updated dataset mask[mask > 18] = self.ignore_index return mask def get_filenames(self, path): """Returns a list of absolute paths to images inside given `path`""" files_list = [] for filename in os.listdir(path): files_list.append(os.path.join(path, filename)) return files_list The provided code snippet includes necessary dependencies for implementing the `_create_synth_kitti_dataset` function. Write a Python function `def _create_synth_kitti_dataset(path_dir: str, image_dims: tuple = (1024, 512))` to solve the following problem: Create synthetic dataset with random images, just to simulate that the dataset have been already downloaded. Here is the function: def _create_synth_kitti_dataset(path_dir: str, image_dims: tuple = (1024, 512)): """Create synthetic dataset with random images, just to simulate that the dataset have been already downloaded.""" path_dir_images = os.path.join(path_dir, KITTI.IMAGE_PATH) path_dir_masks = os.path.join(path_dir, KITTI.MASK_PATH) for p_dir in (path_dir_images, path_dir_masks): os.makedirs(p_dir, exist_ok=True) for i in range(3): path_img = os.path.join(path_dir_images, f"dummy_kitti_{i}.png") Image.new("RGB", image_dims).save(path_img) path_mask = os.path.join(path_dir_masks, f"dummy_kitti_{i}.png") Image.new("L", image_dims).save(path_mask)
Create synthetic dataset with random images, just to simulate that the dataset have been already downloaded.
155,727
import argparse from os import path import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision.transforms as T from lightning.fabric import Fabric, seed_everything from torch.optim.lr_scheduler import StepLR from torchmetrics.classification import Accuracy from torchvision.datasets import MNIST DATASETS_PATH = path.join(path.dirname(__file__), "..", "..", "..", "Datasets") class Net(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.dropout1 = nn.Dropout(0.25) self.dropout2 = nn.Dropout(0.5) self.fc1 = nn.Linear(9216, 128) self.fc2 = nn.Linear(128, 10) def forward(self, x): x = self.conv1(x) x = F.relu(x) x = self.conv2(x) x = F.relu(x) x = F.max_pool2d(x, 2) x = self.dropout1(x) x = torch.flatten(x, 1) x = self.fc1(x) x = F.relu(x) x = self.dropout2(x) x = self.fc2(x) return F.log_softmax(x, dim=1) def run(hparams): # Create the Lightning Fabric object. The parameters like accelerator, strategy, devices etc. will be proided # by the command line. See all options: `fabric run --help` fabric = Fabric() seed_everything(hparams.seed) # instead of torch.manual_seed(...) transform = T.Compose([T.ToTensor(), T.Normalize((0.1307,), (0.3081,))]) # Let rank 0 download the data first, then everyone will load MNIST with fabric.rank_zero_first(local=False): # set `local=True` if your filesystem is not shared between machines train_dataset = MNIST(DATASETS_PATH, download=fabric.is_global_zero, train=True, transform=transform) test_dataset = MNIST(DATASETS_PATH, download=fabric.is_global_zero, train=False, transform=transform) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=hparams.batch_size, ) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=hparams.batch_size) # don't forget to call `setup_dataloaders` to prepare for dataloaders for distributed training. train_loader, test_loader = fabric.setup_dataloaders(train_loader, test_loader) model = Net() # remove call to .to(device) optimizer = optim.Adadelta(model.parameters(), lr=hparams.lr) # don't forget to call `setup` to prepare for model / optimizer for distributed training. # the model is moved automatically to the right device. model, optimizer = fabric.setup(model, optimizer) scheduler = StepLR(optimizer, step_size=1, gamma=hparams.gamma) # use torchmetrics instead of manually computing the accuracy test_acc = Accuracy(task="multiclass", num_classes=10).to(fabric.device) # EPOCH LOOP for epoch in range(1, hparams.epochs + 1): # TRAINING LOOP model.train() for batch_idx, (data, target) in enumerate(train_loader): # NOTE: no need to call `.to(device)` on the data, target optimizer.zero_grad() output = model(data) loss = F.nll_loss(output, target) fabric.backward(loss) # instead of loss.backward() optimizer.step() if (batch_idx == 0) or ((batch_idx + 1) % hparams.log_interval == 0): print( f"Train Epoch: {epoch} [{batch_idx * len(data)}/{len(train_loader.dataset)}" f" ({100.0 * batch_idx / len(train_loader):.0f}%)]\tLoss: {loss.item():.6f}" ) if hparams.dry_run: break scheduler.step() # TESTING LOOP model.eval() test_loss = 0 with torch.no_grad(): for data, target in test_loader: # NOTE: no need to call `.to(device)` on the data, target output = model(data) test_loss += F.nll_loss(output, target, reduction="sum").item() # WITHOUT TorchMetrics # pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability # correct += pred.eq(target.view_as(pred)).sum().item() # WITH TorchMetrics test_acc(output, target) if hparams.dry_run: break # all_gather is used to aggregated the value across processes test_loss = fabric.all_gather(test_loss).sum() / len(test_loader.dataset) print(f"\nTest set: Average loss: {test_loss:.4f}, Accuracy: ({100 * test_acc.compute():.0f}%)\n") test_acc.reset() if hparams.dry_run: break # When using distributed training, use `fabric.save` # to ensure the current process is allowed to save a checkpoint if hparams.save_model: fabric.save(model.state_dict(), "mnist_cnn.pt")
null
155,728
import argparse from os import path import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision.transforms as T from torch.optim.lr_scheduler import StepLR from torchvision.datasets import MNIST DATASETS_PATH = path.join(path.dirname(__file__), "..", "..", "..", "Datasets") class Net(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.dropout1 = nn.Dropout(0.25) self.dropout2 = nn.Dropout(0.5) self.fc1 = nn.Linear(9216, 128) self.fc2 = nn.Linear(128, 10) def forward(self, x): x = self.conv1(x) x = F.relu(x) x = self.conv2(x) x = F.relu(x) x = F.max_pool2d(x, 2) x = self.dropout1(x) x = torch.flatten(x, 1) x = self.fc1(x) x = F.relu(x) x = self.dropout2(x) x = self.fc2(x) return F.log_softmax(x, dim=1) def run(hparams): torch.manual_seed(hparams.seed) use_cuda = torch.cuda.is_available() use_mps = torch.backends.mps.is_available() if use_cuda: device = torch.device("cuda") elif use_mps: device = torch.device("mps") else: device = torch.device("cpu") transform = T.Compose([T.ToTensor(), T.Normalize((0.1307,), (0.3081,))]) train_dataset = MNIST(DATASETS_PATH, train=True, download=True, transform=transform) test_dataset = MNIST(DATASETS_PATH, train=False, transform=transform) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=hparams.batch_size, ) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=hparams.batch_size) model = Net().to(device) optimizer = optim.Adadelta(model.parameters(), lr=hparams.lr) scheduler = StepLR(optimizer, step_size=1, gamma=hparams.gamma) # EPOCH LOOP for epoch in range(1, hparams.epochs + 1): # TRAINING LOOP model.train() for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() if (batch_idx == 0) or ((batch_idx + 1) % hparams.log_interval == 0): print( f"Train Epoch: {epoch} [{batch_idx * len(data)}/{len(train_loader.dataset)}" f" ({100.0 * batch_idx / len(train_loader):.0f}%)]\tLoss: {loss.item():.6f}" ) if hparams.dry_run: break scheduler.step() # TESTING LOOP model.eval() test_loss = 0 correct = 0 with torch.no_grad(): for data, target in test_loader: data, target = data.to(device), target.to(device) output = model(data) test_loss += F.nll_loss(output, target, reduction="sum").item() # sum up batch loss pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability correct += pred.eq(target.view_as(pred)).sum().item() if hparams.dry_run: break test_loss /= len(test_loader.dataset) print( f"\nTest set: Average loss: {test_loss:.4f}, Accuracy: {correct}/{len(test_loader.dataset)}" f" ({100.0 * correct / len(test_loader.dataset):.0f}%)\n" ) if hparams.dry_run: break if hparams.save_model: torch.save(model.state_dict(), "mnist_cnn.pt")
null
155,729
import lightning as L import torch from torchmetrics.functional.classification.accuracy import accuracy from trainer import MyCustomTrainer class MyCustomTrainer: def __init__( self, accelerator: Union[str, Accelerator] = "auto", strategy: Union[str, Strategy] = "auto", devices: Union[List[int], str, int] = "auto", precision: Union[str, int] = "32-true", plugins: Optional[Union[str, Any]] = None, callbacks: Optional[Union[List[Any], Any]] = None, loggers: Optional[Union[Logger, List[Logger]]] = None, max_epochs: Optional[int] = 1000, max_steps: Optional[int] = None, grad_accum_steps: int = 1, limit_train_batches: Union[int, float] = float("inf"), limit_val_batches: Union[int, float] = float("inf"), validation_frequency: int = 1, use_distributed_sampler: bool = True, checkpoint_dir: str = "./checkpoints", checkpoint_frequency: int = 1, ) -> None: def fit( self, model: L.LightningModule, train_loader: torch.utils.data.DataLoader, val_loader: torch.utils.data.DataLoader, ckpt_path: Optional[str] = None, ): def train_loop( self, model: L.LightningModule, optimizer: torch.optim.Optimizer, train_loader: torch.utils.data.DataLoader, limit_batches: Union[int, float] = float("inf"), scheduler_cfg: Optional[Mapping[str, Union[L.fabric.utilities.types.LRScheduler, bool, str, int]]] = None, ): def val_loop( self, model: L.LightningModule, val_loader: Optional[torch.utils.data.DataLoader], limit_batches: Union[int, float] = float("inf"), ): def training_step(self, model: L.LightningModule, batch: Any, batch_idx: int) -> torch.Tensor: def step_scheduler( self, model: L.LightningModule, scheduler_cfg: Optional[Mapping[str, Union[L.fabric.utilities.types.LRScheduler, bool, str, int]]], level: Literal["step", "epoch"], current_value: int, ) -> None: def should_validate(self) -> bool: def progbar_wrapper(self, iterable: Iterable, total: int, **kwargs: Any): def load(self, state: Optional[Mapping], path: str) -> None: def save(self, state: Optional[Mapping]) -> None: def get_latest_checkpoint(checkpoint_dir: str) -> Optional[str]: def _parse_optimizers_schedulers( self, configure_optim_output ) -> Tuple[ Optional[L.fabric.utilities.types.Optimizable], Optional[Mapping[str, Union[L.fabric.utilities.types.LRScheduler, bool, str, int]]], ]: def _format_iterable( prog_bar, candidates: Optional[Union[torch.Tensor, Mapping[str, Union[torch.Tensor, float, int]]]], prefix: str ): def train(model): from torchvision.datasets import MNIST from torchvision.transforms import ToTensor train_set = MNIST(root="/tmp/data/MNIST", train=True, transform=ToTensor(), download=True) val_set = MNIST(root="/tmp/data/MNIST", train=False, transform=ToTensor(), download=False) train_loader = torch.utils.data.DataLoader( train_set, batch_size=64, shuffle=True, pin_memory=torch.cuda.is_available(), num_workers=4 ) val_loader = torch.utils.data.DataLoader( val_set, batch_size=64, shuffle=False, pin_memory=torch.cuda.is_available(), num_workers=4 ) # MPS backend currently does not support all operations used in this example. # If you want to use MPS, set accelerator='auto' and also set PYTORCH_ENABLE_MPS_FALLBACK=1 accelerator = "cpu" if torch.backends.mps.is_available() else "auto" trainer = MyCustomTrainer( accelerator=accelerator, devices="auto", limit_train_batches=10, limit_val_batches=20, max_epochs=3 ) trainer.fit(model, train_loader, val_loader)
null
155,730
import cherry import learn2learn as l2l import torch from lightning.fabric import Fabric, seed_everything def accuracy(predictions, targets): def fast_adapt(batch, learner, loss, adaptation_steps, shots, ways): data, labels = batch # Separate data into adaptation/evalutation sets adaptation_indices = torch.zeros(data.size(0), dtype=bool) adaptation_indices[torch.arange(shots * ways) * 2] = True evaluation_indices = ~adaptation_indices adaptation_data, adaptation_labels = data[adaptation_indices], labels[adaptation_indices] evaluation_data, evaluation_labels = data[evaluation_indices], labels[evaluation_indices] # Adapt the model for step in range(adaptation_steps): train_error = loss(learner(adaptation_data), adaptation_labels) learner.adapt(train_error) # Evaluate the adapted model predictions = learner(evaluation_data) valid_error = loss(predictions, evaluation_labels) valid_accuracy = accuracy(predictions, evaluation_labels) return valid_error, valid_accuracy
null
155,731
import os import random import cherry import learn2learn as l2l import torch import torch.distributed as dist def accuracy(predictions, targets): predictions = predictions.argmax(dim=1).view(targets.shape) return (predictions == targets).sum().float() / targets.size(0) def fast_adapt(batch, learner, loss, adaptation_steps, shots, ways, device): data, labels = batch data, labels = data.to(device), labels.to(device) # Separate data into adaptation/evalutation sets adaptation_indices = torch.zeros(data.size(0), dtype=bool) adaptation_indices[torch.arange(shots * ways) * 2] = True evaluation_indices = ~adaptation_indices adaptation_data, adaptation_labels = data[adaptation_indices], labels[adaptation_indices] evaluation_data, evaluation_labels = data[evaluation_indices], labels[evaluation_indices] # Adapt the model for step in range(adaptation_steps): train_error = loss(learner(adaptation_data), adaptation_labels) learner.adapt(train_error) # Evaluate the adapted model predictions = learner(evaluation_data) valid_error = loss(predictions, evaluation_labels) valid_accuracy = accuracy(predictions, evaluation_labels) return valid_error, valid_accuracy
null
155,732
import os import time from pathlib import Path import torch import torch.nn as nn import torch.nn.parallel import torch.optim as optim import torch.utils.data import torchvision.transforms as transforms import torchvision.utils from lightning.fabric import Fabric, seed_everything from torchvision.datasets import CelebA def weights_init(m): # custom weights initialization called on netG and netD classname = m.__class__.__name__ if classname.find("Conv") != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find("BatchNorm") != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0)
null
155,733
import os import random import time from pathlib import Path import torch import torch.nn as nn import torch.nn.parallel import torch.optim as optim import torch.utils.data import torchvision.transforms as transforms import torchvision.utils from torchvision.datasets import CelebA def weights_init(m): # custom weights initialization called on netG and netD classname = m.__class__.__name__ if classname.find("Conv") != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find("BatchNorm") != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0)
null
155,734
import lightning as L import torch import torch.nn.functional as F from lightning.pytorch.demos import Transformer, WikiText2 from torch.utils.data import DataLoader, random_split def get_dataloaders(dataset): n = len(dataset) generator = torch.Generator().manual_seed(42) train_dataset, val_dataset, test_dataset = random_split(dataset, [n - 4000, 2000, 2000], generator=generator) train_dataloader = DataLoader(train_dataset, batch_size=20, shuffle=True) val_dataloader = DataLoader(val_dataset, batch_size=20, shuffle=False) test_dataloader = DataLoader(test_dataset, batch_size=20, shuffle=False) return train_dataloader, val_dataloader, test_dataloader
null
155,735
import argparse from os import path import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision.transforms as T from lightning.fabric import Fabric, seed_everything from sklearn import model_selection from torch.utils.data import DataLoader, SubsetRandomSampler from torchmetrics.classification import Accuracy from torchvision.datasets import MNIST DATASETS_PATH = path.join(path.dirname(__file__), "..", "..", "..", "Datasets") class Net(nn.Module): def __init__(self) -> None: def forward(self, x): def train_dataloader(model, data_loader, optimizer, fabric, epoch, hparams, fold): def validate_dataloader(model, data_loader, fabric, hparams, fold, acc_metric): def run(hparams): # Create the Lightning Fabric object. The parameters like accelerator, strategy, devices etc. will be proided # by the command line. See all options: `fabric run --help` fabric = Fabric() seed_everything(hparams.seed) # instead of torch.manual_seed(...) transform = T.Compose([T.ToTensor(), T.Normalize((0.1307,), (0.3081,))]) # Let rank 0 download the data first, then everyone will load MNIST with fabric.rank_zero_first(local=False): # set `local=True` if your filesystem is not shared between machines dataset = MNIST(DATASETS_PATH, train=True, download=True, transform=transform) # Loop over different folds (shuffle = False by default so reproducible) folds = hparams.folds kfold = model_selection.KFold(n_splits=folds) # initialize n_splits models and optimizers models = [Net() for _ in range(kfold.n_splits)] optimizers = [optim.Adadelta(model.parameters(), lr=hparams.lr) for model in models] # fabric setup for models and optimizers for i in range(kfold.n_splits): models[i], optimizers[i] = fabric.setup(models[i], optimizers[i]) # Accuracy using torchmetrics acc_metric = Accuracy(task="multiclass", num_classes=10).to(fabric.device) # loop over epochs for epoch in range(1, hparams.epochs + 1): # loop over folds epoch_acc = 0 for fold, (train_ids, val_ids) in enumerate(kfold.split(dataset)): print(f"Working on fold {fold}") # initialize dataloaders based on folds batch_size = hparams.batch_size train_loader = DataLoader(dataset, batch_size=batch_size, sampler=SubsetRandomSampler(train_ids)) val_loader = DataLoader(dataset, batch_size=batch_size, sampler=SubsetRandomSampler(val_ids)) # set up dataloaders to move data to the correct device train_loader, val_loader = fabric.setup_dataloaders(train_loader, val_loader) # get model and optimizer for the current fold model, optimizer = models[fold], optimizers[fold] # train and validate train_dataloader(model, train_loader, optimizer, fabric, epoch, hparams, fold) epoch_acc += validate_dataloader(model, val_loader, fabric, hparams, fold, acc_metric) acc_metric.reset() # log epoch metrics print(f"Epoch {epoch} - Average acc: {epoch_acc / kfold.n_splits}") if hparams.dry_run: break # When using distributed training, use `fabric.save` # to ensure the current process is allowed to save a checkpoint if hparams.save_model: fabric.save(model.state_dict(), "mnist_cnn.pt")
null
155,736
import argparse import math import os from distutils.util import strtobool from typing import TYPE_CHECKING, Optional, Union import gymnasium as gym import torch from torch.utils.tensorboard import SummaryWriter def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--exp-name", type=str, default="default", help="the name of this experiment") # PyTorch arguments parser.add_argument("--seed", type=int, default=42, help="seed of the experiment") parser.add_argument( "--cuda", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True, help="If toggled, GPU training will be used. " "This affects also the distributed backend used (NCCL (gpu) vs GLOO (cpu))", ) parser.add_argument( "--player-on-gpu", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True, help="If toggled, player will run on GPU (used only by `train_fabric_decoupled.py` script). " "This affects also the distributed backend used (NCCL (gpu) vs GLOO (cpu))", ) parser.add_argument( "--torch-deterministic", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True, help="if toggled, `torch.backends.cudnn.deterministic=False`", ) # Distributed arguments parser.add_argument("--num-envs", type=int, default=2, help="the number of parallel game environments") parser.add_argument( "--share-data", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True, help="Toggle sharing data between processes", ) parser.add_argument("--per-rank-batch-size", type=int, default=64, help="the batch size for each rank") # Environment arguments parser.add_argument("--env-id", type=str, default="CartPole-v1", help="the id of the environment") parser.add_argument( "--num-steps", type=int, default=128, help="the number of steps to run in each environment per policy rollout" ) parser.add_argument( "--capture-video", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True, help="whether to capture videos of the agent performances (check out `videos` folder)", ) # PPO arguments parser.add_argument("--total-timesteps", type=int, default=2**16, help="total timesteps of the experiments") parser.add_argument("--learning-rate", type=float, default=1e-3, help="the learning rate of the optimizer") parser.add_argument( "--anneal-lr", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True, help="Toggle learning rate annealing for policy and value networks", ) parser.add_argument("--gamma", type=float, default=0.99, help="the discount factor gamma") parser.add_argument( "--gae-lambda", type=float, default=0.95, help="the lambda for the general advantage estimation" ) parser.add_argument("--update-epochs", type=int, default=10, help="the K epochs to update the policy") parser.add_argument( "--activation-function", type=str, default="relu", choices=["relu", "tanh"], help="The activation function of the model", ) parser.add_argument( "--ortho-init", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True, help="Toggles the orthogonal initialization of the model", ) parser.add_argument( "--normalize-advantages", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True, help="Toggles advantages normalization", ) parser.add_argument("--clip-coef", type=float, default=0.2, help="the surrogate clipping coefficient") parser.add_argument( "--clip-vloss", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True, help="Toggles whether or not to use a clipped loss for the value function, as per the paper.", ) parser.add_argument("--ent-coef", type=float, default=0.0, help="coefficient of the entropy") parser.add_argument("--vf-coef", type=float, default=1.0, help="coefficient of the value function") parser.add_argument("--max-grad-norm", type=float, default=0.5, help="the maximum norm for the gradient clipping") return parser.parse_args()
null
155,737
import argparse import math import os from distutils.util import strtobool from typing import TYPE_CHECKING, Optional, Union import gymnasium as gym import torch from torch.utils.tensorboard import SummaryWriter def layer_init( layer: torch.nn.Module, std: float = math.sqrt(2), bias_const: float = 0.0, ortho_init: bool = True, ): if ortho_init: torch.nn.init.orthogonal_(layer.weight, std) torch.nn.init.constant_(layer.bias, bias_const) return layer
null
155,738
import argparse import os import time from datetime import datetime from typing import Dict import gymnasium as gym import torch import torchmetrics from lightning.fabric import Fabric from lightning.fabric.loggers import TensorBoardLogger from rl.agent import PPOLightningAgent from rl.utils import linear_annealing, make_env, parse_args, test from torch import Tensor from torch.utils.data import BatchSampler, DistributedSampler, RandomSampler class PPOLightningAgent(LightningModule): def __init__( self, envs: gym.vector.SyncVectorEnv, act_fun: str = "relu", ortho_init: bool = False, vf_coef: float = 1.0, ent_coef: float = 0.0, clip_coef: float = 0.2, clip_vloss: bool = False, normalize_advantages: bool = False, **torchmetrics_kwargs, ): super().__init__() if act_fun.lower() == "relu": act_fun = torch.nn.ReLU() elif act_fun.lower() == "tanh": act_fun = torch.nn.Tanh() else: raise ValueError("Unrecognized activation function: `act_fun` must be either `relu` or `tanh`") self.vf_coef = vf_coef self.ent_coef = ent_coef self.clip_coef = clip_coef self.clip_vloss = clip_vloss self.normalize_advantages = normalize_advantages self.critic = torch.nn.Sequential( layer_init( torch.nn.Linear(math.prod(envs.single_observation_space.shape), 64), ortho_init=ortho_init, ), act_fun, layer_init(torch.nn.Linear(64, 64), ortho_init=ortho_init), act_fun, layer_init(torch.nn.Linear(64, 1), std=1.0, ortho_init=ortho_init), ) self.actor = torch.nn.Sequential( layer_init( torch.nn.Linear(math.prod(envs.single_observation_space.shape), 64), ortho_init=ortho_init, ), act_fun, layer_init(torch.nn.Linear(64, 64), ortho_init=ortho_init), act_fun, layer_init(torch.nn.Linear(64, envs.single_action_space.n), std=0.01, ortho_init=ortho_init), ) self.avg_pg_loss = MeanMetric(**torchmetrics_kwargs) self.avg_value_loss = MeanMetric(**torchmetrics_kwargs) self.avg_ent_loss = MeanMetric(**torchmetrics_kwargs) def get_action(self, x: Tensor, action: Tensor = None) -> Tuple[Tensor, Tensor, Tensor]: logits = self.actor(x) distribution = Categorical(logits=logits) if action is None: action = distribution.sample() return action, distribution.log_prob(action), distribution.entropy() def get_greedy_action(self, x: Tensor) -> Tensor: logits = self.actor(x) probs = F.softmax(logits, dim=-1) return torch.argmax(probs, dim=-1) def get_value(self, x: Tensor) -> Tensor: return self.critic(x) def get_action_and_value(self, x: Tensor, action: Tensor = None) -> Tuple[Tensor, Tensor, Tensor, Tensor]: action, log_prob, entropy = self.get_action(x, action) value = self.get_value(x) return action, log_prob, entropy, value def forward(self, x: Tensor, action: Tensor = None) -> Tuple[Tensor, Tensor, Tensor, Tensor]: return self.get_action_and_value(x, action) def estimate_returns_and_advantages( self, rewards: Tensor, values: Tensor, dones: Tensor, next_obs: Tensor, next_done: Tensor, num_steps: int, gamma: float, gae_lambda: float, ) -> Tuple[Tensor, Tensor]: next_value = self.get_value(next_obs).reshape(1, -1) advantages = torch.zeros_like(rewards) lastgaelam = 0 for t in reversed(range(num_steps)): if t == num_steps - 1: nextnonterminal = torch.logical_not(next_done) nextvalues = next_value else: nextnonterminal = torch.logical_not(dones[t + 1]) nextvalues = values[t + 1] delta = rewards[t] + gamma * nextvalues * nextnonterminal - values[t] advantages[t] = lastgaelam = delta + gamma * gae_lambda * nextnonterminal * lastgaelam returns = advantages + values return returns, advantages def training_step(self, batch: Dict[str, Tensor]): # Get actions and values given the current observations _, newlogprob, entropy, newvalue = self(batch["obs"], batch["actions"].long()) logratio = newlogprob - batch["logprobs"] ratio = logratio.exp() # Policy loss advantages = batch["advantages"] if self.normalize_advantages: advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8) pg_loss = policy_loss(batch["advantages"], ratio, self.clip_coef) # Value loss v_loss = value_loss( newvalue, batch["values"], batch["returns"], self.clip_coef, self.clip_vloss, self.vf_coef, ) # Entropy loss ent_loss = entropy_loss(entropy, self.ent_coef) # Update metrics self.avg_pg_loss(pg_loss) self.avg_value_loss(v_loss) self.avg_ent_loss(ent_loss) # Overall loss return pg_loss + ent_loss + v_loss def on_train_epoch_end(self, global_step: int) -> None: # Log metrics and reset their internal state self.logger.log_metrics( { "Loss/policy_loss": self.avg_pg_loss.compute(), "Loss/value_loss": self.avg_value_loss.compute(), "Loss/entropy_loss": self.avg_ent_loss.compute(), }, global_step, ) self.reset_metrics() def reset_metrics(self): self.avg_pg_loss.reset() self.avg_value_loss.reset() self.avg_ent_loss.reset() def configure_optimizers(self, lr: float): return torch.optim.Adam(self.parameters(), lr=lr, eps=1e-4) def train( fabric: Fabric, agent: PPOLightningAgent, optimizer: torch.optim.Optimizer, data: Dict[str, Tensor], global_step: int, args: argparse.Namespace, ): indexes = list(range(data["obs"].shape[0])) if args.share_data: sampler = DistributedSampler( indexes, num_replicas=fabric.world_size, rank=fabric.global_rank, shuffle=True, seed=args.seed ) else: sampler = RandomSampler(indexes) sampler = BatchSampler(sampler, batch_size=args.per_rank_batch_size, drop_last=False) for epoch in range(args.update_epochs): if args.share_data: sampler.sampler.set_epoch(epoch) for batch_idxes in sampler: loss = agent.training_step({k: v[batch_idxes] for k, v in data.items()}) optimizer.zero_grad(set_to_none=True) fabric.backward(loss) fabric.clip_gradients(agent, optimizer, max_norm=args.max_grad_norm) optimizer.step() agent.on_train_epoch_end(global_step)
null
155,739
import argparse import os import time from contextlib import nullcontext from datetime import datetime import gymnasium as gym import torch from lightning.fabric import Fabric from lightning.fabric.loggers import TensorBoardLogger from lightning.fabric.plugins.collectives import TorchCollective from lightning.fabric.plugins.collectives.collective import CollectibleGroup from lightning.fabric.strategies import DDPStrategy from rl.agent import PPOLightningAgent from rl.utils import linear_annealing, make_env, parse_args, test from torch.distributed.algorithms.join import Join from torch.utils.data import BatchSampler, DistributedSampler, RandomSampler from torchmetrics import MeanMetric class PPOLightningAgent(LightningModule): def __init__( self, envs: gym.vector.SyncVectorEnv, act_fun: str = "relu", ortho_init: bool = False, vf_coef: float = 1.0, ent_coef: float = 0.0, clip_coef: float = 0.2, clip_vloss: bool = False, normalize_advantages: bool = False, **torchmetrics_kwargs, ): def get_action(self, x: Tensor, action: Tensor = None) -> Tuple[Tensor, Tensor, Tensor]: def get_greedy_action(self, x: Tensor) -> Tensor: def get_value(self, x: Tensor) -> Tensor: def get_action_and_value(self, x: Tensor, action: Tensor = None) -> Tuple[Tensor, Tensor, Tensor, Tensor]: def forward(self, x: Tensor, action: Tensor = None) -> Tuple[Tensor, Tensor, Tensor, Tensor]: def estimate_returns_and_advantages( self, rewards: Tensor, values: Tensor, dones: Tensor, next_obs: Tensor, next_done: Tensor, num_steps: int, gamma: float, gae_lambda: float, ) -> Tuple[Tensor, Tensor]: def training_step(self, batch: Dict[str, Tensor]): def on_train_epoch_end(self, global_step: int) -> None: def reset_metrics(self): def configure_optimizers(self, lr: float): def make_env(env_id: str, seed: int, idx: int, capture_video: bool, run_name: Optional[str] = None, prefix: str = ""): def test( agent: Union["PPOLightningAgent", "PPOAgent"], device: torch.device, logger: SummaryWriter, args: argparse.Namespace ): def player(args, world_collective: TorchCollective, player_trainer_collective: TorchCollective): run_name = f"{args.env_id}_{args.exp_name}_{args.seed}" logger = TensorBoardLogger( root_dir=os.path.join("logs", "fabric_decoupled_logs", datetime.today().strftime("%Y-%m-%d_%H-%M-%S")), name=run_name, ) log_dir = logger.log_dir # Initialize Fabric object fabric = Fabric(loggers=logger, accelerator="cuda" if args.player_on_gpu else "cpu") device = fabric.device fabric.seed_everything(args.seed) torch.backends.cudnn.deterministic = args.torch_deterministic # Log hyperparameters logger.experiment.add_text( "hyperparameters", "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])), ) # Environment setup envs = gym.vector.SyncVectorEnv([ make_env(args.env_id, args.seed + i, 0, args.capture_video, log_dir, "train") for i in range(args.num_envs) ]) assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported" # Define the agent agent: PPOLightningAgent = PPOLightningAgent( envs, act_fun=args.activation_function, vf_coef=args.vf_coef, ent_coef=args.ent_coef, clip_coef=args.clip_coef, clip_vloss=args.clip_vloss, ortho_init=args.ortho_init, normalize_advantages=args.normalize_advantages, ).to(device) flattened_parameters = torch.empty_like( torch.nn.utils.convert_parameters.parameters_to_vector(agent.parameters()), device=device ) # Receive the first weights from the rank-1, a.k.a. the first of the trainers # In this way we are sure that before the first iteration everyone starts with the same parameters player_trainer_collective.broadcast(flattened_parameters, src=1) torch.nn.utils.convert_parameters.vector_to_parameters(flattened_parameters, agent.parameters()) # Player metrics rew_avg = MeanMetric(sync_on_compute=False).to(device) ep_len_avg = MeanMetric(sync_on_compute=False).to(device) # Local data obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device) actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device) logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device) rewards = torch.zeros((args.num_steps, args.num_envs)).to(device) dones = torch.zeros((args.num_steps, args.num_envs)).to(device) values = torch.zeros((args.num_steps, args.num_envs)).to(device) # Global variables global_step = 0 start_time = time.time() single_global_step = int(args.num_envs * args.num_steps) num_updates = args.total_timesteps // single_global_step if not args.share_data: if single_global_step < world_collective.world_size - 1: raise RuntimeError( f"The number of trainers ({world_collective.world_size - 1})" f" is greater than the available collected data ({single_global_step})." f" Consider to lower the number of trainers at least to the size of available collected data" ) chunks_sizes = [ len(chunk) for chunk in torch.tensor_split(torch.arange(single_global_step), world_collective.world_size - 1) ] # Broadcast num_updates to all the world update_t = torch.tensor([num_updates], device=device, dtype=torch.float32) world_collective.broadcast(update_t, src=0) # Get the first environment observation and start the optimization next_obs = torch.tensor(envs.reset(seed=args.seed)[0], device=device) next_done = torch.zeros(args.num_envs).to(device) for _ in range(1, num_updates + 1): for step in range(0, args.num_steps): global_step += args.num_envs obs[step] = next_obs dones[step] = next_done # Sample an action given the observation received by the environment action, logprob, _, value = agent.get_action_and_value(next_obs) values[step] = value.flatten() actions[step] = action logprobs[step] = logprob # Single environment step next_obs, reward, done, truncated, info = envs.step(action.cpu().numpy()) done = torch.logical_or(torch.tensor(done), torch.tensor(truncated)) rewards[step] = torch.tensor(reward, device=device).view(-1) next_obs, next_done = torch.tensor(next_obs, device=device), done.to(device) if "final_info" in info: for i, agent_final_info in enumerate(info["final_info"]): if agent_final_info is not None and "episode" in agent_final_info: fabric.print( f"Rank-0: global_step={global_step}, reward_env_{i}={agent_final_info['episode']['r'][0]}" ) rew_avg(agent_final_info["episode"]["r"][0]) ep_len_avg(agent_final_info["episode"]["l"][0]) # Sync the metrics rew_avg_reduced = rew_avg.compute() if not rew_avg_reduced.isnan(): fabric.log("Rewards/rew_avg", rew_avg_reduced, global_step) ep_len_avg_reduced = ep_len_avg.compute() if not ep_len_avg_reduced.isnan(): fabric.log("Game/ep_len_avg", ep_len_avg_reduced, global_step) rew_avg.reset() ep_len_avg.reset() # Estimate returns with GAE (https://arxiv.org/abs/1506.02438) returns, advantages = agent.estimate_returns_and_advantages( rewards, values, dones, next_obs, next_done, args.num_steps, args.gamma, args.gae_lambda ) # Flatten the batch local_data = { "obs": obs.reshape((-1,) + envs.single_observation_space.shape), "logprobs": logprobs.reshape(-1), "actions": actions.reshape((-1,) + envs.single_action_space.shape), "advantages": advantages.reshape(-1), "returns": returns.reshape(-1), "values": values.reshape(-1), } if not args.player_on_gpu and args.cuda: for v in local_data.values(): v = v.pin_memory() # Send data to the training agents if args.share_data: world_collective.broadcast_object_list([local_data], src=0) else: # Split data in an even way, when possible perm = torch.randperm(single_global_step, device=device) chunks = [{} for _ in range(world_collective.world_size - 1)] for k, v in local_data.items(): chunked_local_data = v[perm].split(chunks_sizes) for i in range(len(chunks)): chunks[i][k] = chunked_local_data[i] world_collective.scatter_object_list([None], [None] + chunks, src=0) # Gather metrics from the trainers to be plotted metrics = [None] player_trainer_collective.broadcast_object_list(metrics, src=1) # Wait the trainers to finish player_trainer_collective.broadcast(flattened_parameters, src=1) # Convert back the parameters torch.nn.utils.convert_parameters.vector_to_parameters(flattened_parameters, agent.parameters()) fabric.log_dict(metrics[0], global_step) fabric.log_dict({"Time/step_per_second": int(global_step / (time.time() - start_time))}, global_step) if args.share_data: world_collective.broadcast_object_list([-1], src=0) else: world_collective.scatter_object_list([None], [None] + [-1] * (world_collective.world_size - 1), src=0) envs.close() test(agent, device, fabric.logger.experiment, args)
null
155,740
import argparse import os import time from contextlib import nullcontext from datetime import datetime import gymnasium as gym import torch from lightning.fabric import Fabric from lightning.fabric.loggers import TensorBoardLogger from lightning.fabric.plugins.collectives import TorchCollective from lightning.fabric.plugins.collectives.collective import CollectibleGroup from lightning.fabric.strategies import DDPStrategy from rl.agent import PPOLightningAgent from rl.utils import linear_annealing, make_env, parse_args, test from torch.distributed.algorithms.join import Join from torch.utils.data import BatchSampler, DistributedSampler, RandomSampler from torchmetrics import MeanMetric class PPOLightningAgent(LightningModule): def __init__( self, envs: gym.vector.SyncVectorEnv, act_fun: str = "relu", ortho_init: bool = False, vf_coef: float = 1.0, ent_coef: float = 0.0, clip_coef: float = 0.2, clip_vloss: bool = False, normalize_advantages: bool = False, **torchmetrics_kwargs, ): super().__init__() if act_fun.lower() == "relu": act_fun = torch.nn.ReLU() elif act_fun.lower() == "tanh": act_fun = torch.nn.Tanh() else: raise ValueError("Unrecognized activation function: `act_fun` must be either `relu` or `tanh`") self.vf_coef = vf_coef self.ent_coef = ent_coef self.clip_coef = clip_coef self.clip_vloss = clip_vloss self.normalize_advantages = normalize_advantages self.critic = torch.nn.Sequential( layer_init( torch.nn.Linear(math.prod(envs.single_observation_space.shape), 64), ortho_init=ortho_init, ), act_fun, layer_init(torch.nn.Linear(64, 64), ortho_init=ortho_init), act_fun, layer_init(torch.nn.Linear(64, 1), std=1.0, ortho_init=ortho_init), ) self.actor = torch.nn.Sequential( layer_init( torch.nn.Linear(math.prod(envs.single_observation_space.shape), 64), ortho_init=ortho_init, ), act_fun, layer_init(torch.nn.Linear(64, 64), ortho_init=ortho_init), act_fun, layer_init(torch.nn.Linear(64, envs.single_action_space.n), std=0.01, ortho_init=ortho_init), ) self.avg_pg_loss = MeanMetric(**torchmetrics_kwargs) self.avg_value_loss = MeanMetric(**torchmetrics_kwargs) self.avg_ent_loss = MeanMetric(**torchmetrics_kwargs) def get_action(self, x: Tensor, action: Tensor = None) -> Tuple[Tensor, Tensor, Tensor]: logits = self.actor(x) distribution = Categorical(logits=logits) if action is None: action = distribution.sample() return action, distribution.log_prob(action), distribution.entropy() def get_greedy_action(self, x: Tensor) -> Tensor: logits = self.actor(x) probs = F.softmax(logits, dim=-1) return torch.argmax(probs, dim=-1) def get_value(self, x: Tensor) -> Tensor: return self.critic(x) def get_action_and_value(self, x: Tensor, action: Tensor = None) -> Tuple[Tensor, Tensor, Tensor, Tensor]: action, log_prob, entropy = self.get_action(x, action) value = self.get_value(x) return action, log_prob, entropy, value def forward(self, x: Tensor, action: Tensor = None) -> Tuple[Tensor, Tensor, Tensor, Tensor]: return self.get_action_and_value(x, action) def estimate_returns_and_advantages( self, rewards: Tensor, values: Tensor, dones: Tensor, next_obs: Tensor, next_done: Tensor, num_steps: int, gamma: float, gae_lambda: float, ) -> Tuple[Tensor, Tensor]: next_value = self.get_value(next_obs).reshape(1, -1) advantages = torch.zeros_like(rewards) lastgaelam = 0 for t in reversed(range(num_steps)): if t == num_steps - 1: nextnonterminal = torch.logical_not(next_done) nextvalues = next_value else: nextnonterminal = torch.logical_not(dones[t + 1]) nextvalues = values[t + 1] delta = rewards[t] + gamma * nextvalues * nextnonterminal - values[t] advantages[t] = lastgaelam = delta + gamma * gae_lambda * nextnonterminal * lastgaelam returns = advantages + values return returns, advantages def training_step(self, batch: Dict[str, Tensor]): # Get actions and values given the current observations _, newlogprob, entropy, newvalue = self(batch["obs"], batch["actions"].long()) logratio = newlogprob - batch["logprobs"] ratio = logratio.exp() # Policy loss advantages = batch["advantages"] if self.normalize_advantages: advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8) pg_loss = policy_loss(batch["advantages"], ratio, self.clip_coef) # Value loss v_loss = value_loss( newvalue, batch["values"], batch["returns"], self.clip_coef, self.clip_vloss, self.vf_coef, ) # Entropy loss ent_loss = entropy_loss(entropy, self.ent_coef) # Update metrics self.avg_pg_loss(pg_loss) self.avg_value_loss(v_loss) self.avg_ent_loss(ent_loss) # Overall loss return pg_loss + ent_loss + v_loss def on_train_epoch_end(self, global_step: int) -> None: # Log metrics and reset their internal state self.logger.log_metrics( { "Loss/policy_loss": self.avg_pg_loss.compute(), "Loss/value_loss": self.avg_value_loss.compute(), "Loss/entropy_loss": self.avg_ent_loss.compute(), }, global_step, ) self.reset_metrics() def reset_metrics(self): self.avg_pg_loss.reset() self.avg_value_loss.reset() self.avg_ent_loss.reset() def configure_optimizers(self, lr: float): return torch.optim.Adam(self.parameters(), lr=lr, eps=1e-4) def linear_annealing(optimizer: torch.optim.Optimizer, update: int, num_updates: int, initial_lr: float): frac = 1.0 - (update - 1.0) / num_updates lrnow = frac * initial_lr for pg in optimizer.param_groups: pg["lr"] = lrnow def make_env(env_id: str, seed: int, idx: int, capture_video: bool, run_name: Optional[str] = None, prefix: str = ""): def thunk(): env = gym.make(env_id, render_mode="rgb_array") env = gym.wrappers.RecordEpisodeStatistics(env) if capture_video and idx == 0 and run_name is not None: env = gym.wrappers.RecordVideo( env, os.path.join(run_name, prefix + "_videos" if prefix else "videos"), disable_logger=True ) env.action_space.seed(seed) env.observation_space.seed(seed) return env return thunk def trainer( args, world_collective: TorchCollective, player_trainer_collective: TorchCollective, optimization_pg: CollectibleGroup, ): global_rank = world_collective.rank group_rank = global_rank - 1 group_world_size = world_collective.world_size - 1 # Initialize Fabric fabric = Fabric(strategy=DDPStrategy(process_group=optimization_pg), accelerator="cuda" if args.cuda else "cpu") device = fabric.device fabric.seed_everything(args.seed) torch.backends.cudnn.deterministic = args.torch_deterministic # Environment setup envs = gym.vector.SyncVectorEnv([make_env(args.env_id, 0, 0, False, None)]) assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported" # Define the agent and the optimizer and setup them with Fabric agent: PPOLightningAgent = PPOLightningAgent( envs, act_fun=args.activation_function, vf_coef=args.vf_coef, ent_coef=args.ent_coef, clip_coef=args.clip_coef, clip_vloss=args.clip_vloss, ortho_init=args.ortho_init, normalize_advantages=args.normalize_advantages, process_group=optimization_pg, ) optimizer = agent.configure_optimizers(args.learning_rate) agent, optimizer = fabric.setup(agent, optimizer) # Send weights to rank-0, a.k.a. the player if global_rank == 1: player_trainer_collective.broadcast( torch.nn.utils.convert_parameters.parameters_to_vector(agent.parameters()), src=1 ) # Receive maximum number of updates from the player update = 0 num_updates = torch.zeros(1, device=device) world_collective.broadcast(num_updates, src=0) num_updates = num_updates.item() # Start training while True: # Wait for data data = [None] if args.share_data: world_collective.broadcast_object_list(data, src=0) else: world_collective.scatter_object_list(data, [None for _ in range(world_collective.world_size)], src=0) data = data[0] if data == -1: return # Metrics dict to be sent to the player if group_rank == 0: metrics = {} # Lerning rate annealing if args.anneal_lr: linear_annealing(optimizer, update, num_updates, args.learning_rate) if group_rank == 0: metrics["Info/learning_rate"] = optimizer.param_groups[0]["lr"] update += 1 indexes = list(range(data["obs"].shape[0])) if args.share_data: sampler = DistributedSampler( indexes, num_replicas=group_world_size, rank=group_rank, shuffle=True, seed=args.seed, drop_last=False ) else: sampler = RandomSampler(indexes) sampler = BatchSampler(sampler, batch_size=args.per_rank_batch_size, drop_last=False) # The Join context is needed because there can be the possibility # that some ranks receive less data with Join([agent._forward_module]) if not args.share_data else nullcontext(): for epoch in range(args.update_epochs): if args.share_data: sampler.sampler.set_epoch(epoch) for batch_idxes in sampler: loss = agent.training_step({k: v[batch_idxes].to(device) for k, v in data.items()}) optimizer.zero_grad(set_to_none=True) fabric.backward(loss) fabric.clip_gradients(agent, optimizer, max_norm=args.max_grad_norm) optimizer.step() # Sync metrics avg_pg_loss = agent.avg_pg_loss.compute() avg_value_loss = agent.avg_value_loss.compute() avg_ent_loss = agent.avg_ent_loss.compute() agent.reset_metrics() # Send updated weights to the player if global_rank == 1: metrics["Loss/policy_loss"] = avg_pg_loss metrics["Loss/value_loss"] = avg_value_loss metrics["Loss/entropy_loss"] = avg_ent_loss player_trainer_collective.broadcast_object_list( [metrics], src=1 ) # Broadcast metrics: fake send with object list between rank-0 and rank-1 player_trainer_collective.broadcast( torch.nn.utils.convert_parameters.parameters_to_vector(agent.parameters()), src=1 )
null
155,741
import argparse import os import random import time from datetime import datetime from typing import Dict import gymnasium as gym import torch import torch.distributed as distributed import torch.nn as nn import torch.optim as optim from rl.agent import PPOAgent from rl.loss import entropy_loss, policy_loss, value_loss from rl.utils import linear_annealing, make_env, parse_args, test from torch import Tensor from torch.nn.parallel import DistributedDataParallel from torch.utils.data import BatchSampler, DistributedSampler, RandomSampler from torch.utils.tensorboard import SummaryWriter class PPOAgent(torch.nn.Module): def __init__(self, envs: gym.vector.SyncVectorEnv, act_fun: str = "relu", ortho_init: bool = False) -> None: super().__init__() if act_fun.lower() == "relu": act_fun = torch.nn.ReLU() elif act_fun.lower() == "tanh": act_fun = torch.nn.Tanh() else: raise ValueError("Unrecognized activation function: `act_fun` must be either `relu` or `tanh`") self.critic = torch.nn.Sequential( layer_init( torch.nn.Linear(math.prod(envs.single_observation_space.shape), 64), ortho_init=ortho_init, ), act_fun, layer_init(torch.nn.Linear(64, 64), ortho_init=ortho_init), act_fun, layer_init(torch.nn.Linear(64, 1), std=1.0, ortho_init=ortho_init), ) self.actor = torch.nn.Sequential( layer_init( torch.nn.Linear(math.prod(envs.single_observation_space.shape), 64), ortho_init=ortho_init, ), act_fun, layer_init(torch.nn.Linear(64, 64), ortho_init=ortho_init), act_fun, layer_init(torch.nn.Linear(64, envs.single_action_space.n), std=0.01, ortho_init=ortho_init), ) def get_action(self, x: Tensor, action: Tensor = None) -> Tuple[Tensor, Tensor, Tensor]: logits = self.actor(x) distribution = Categorical(logits=logits) if action is None: action = distribution.sample() return action, distribution.log_prob(action), distribution.entropy() def get_greedy_action(self, x: Tensor) -> Tensor: logits = self.actor(x) probs = F.softmax(logits, dim=-1) return torch.argmax(probs, dim=-1) def get_value(self, x: Tensor) -> Tensor: return self.critic(x) def get_action_and_value(self, x: Tensor, action: Tensor = None) -> Tuple[Tensor, Tensor, Tensor, Tensor]: action, log_prob, entropy = self.get_action(x, action) value = self.get_value(x) return action, log_prob, entropy, value def forward(self, x: Tensor, action: Tensor = None) -> Tuple[Tensor, Tensor, Tensor, Tensor]: return self.get_action_and_value(x, action) def estimate_returns_and_advantages( self, rewards: Tensor, values: Tensor, dones: Tensor, next_obs: Tensor, next_done: Tensor, num_steps: int, gamma: float, gae_lambda: float, ) -> Tuple[Tensor, Tensor]: next_value = self.get_value(next_obs).reshape(1, -1) advantages = torch.zeros_like(rewards) lastgaelam = 0 for t in reversed(range(num_steps)): if t == num_steps - 1: nextnonterminal = torch.logical_not(next_done) nextvalues = next_value else: nextnonterminal = torch.logical_not(dones[t + 1]) nextvalues = values[t + 1] delta = rewards[t] + gamma * nextvalues * nextnonterminal - values[t] advantages[t] = lastgaelam = delta + gamma * gae_lambda * nextnonterminal * lastgaelam returns = advantages + values return returns, advantages def policy_loss(advantages: torch.Tensor, ratio: torch.Tensor, clip_coef: float) -> torch.Tensor: pg_loss1 = -advantages * ratio pg_loss2 = -advantages * torch.clamp(ratio, 1 - clip_coef, 1 + clip_coef) return torch.max(pg_loss1, pg_loss2).mean() def value_loss( new_values: Tensor, old_values: Tensor, returns: Tensor, clip_coef: float, clip_vloss: bool, vf_coef: float, ) -> Tensor: new_values = new_values.view(-1) if not clip_vloss: values_pred = new_values else: values_pred = old_values + torch.clamp(new_values - old_values, -clip_coef, clip_coef) return vf_coef * F.mse_loss(values_pred, returns) def entropy_loss(entropy: Tensor, ent_coef: float) -> Tensor: return -entropy.mean() * ent_coef def train( agent: PPOAgent, optimizer: torch.optim.Optimizer, data: Dict[str, Tensor], logger: SummaryWriter, global_step: int, args: argparse.Namespace, ): indexes = list(range(data["obs"].shape[0])) if args.share_data: sampler = DistributedSampler( indexes, num_replicas=distributed.get_world_size(), rank=distributed.get_rank(), shuffle=True, seed=args.seed, ) else: sampler = RandomSampler(indexes) sampler = BatchSampler(sampler, batch_size=args.per_rank_batch_size, drop_last=False) per_epoch_losses = torch.tensor([0.0, 0.0, 0.0], device=data["obs"].device) for epoch in range(args.update_epochs): if args.share_data: sampler.sampler.set_epoch(epoch) for batch_idxes in sampler: _, newlogprob, entropy, newvalue = agent(data["obs"][batch_idxes], data["actions"].long()[batch_idxes]) logratio = newlogprob - data["logprobs"][batch_idxes] ratio = logratio.exp() advantages = data["advantages"][batch_idxes] if args.normalize_advantages: advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8) # Policy loss pg_loss = policy_loss(advantages, ratio, args.clip_coef) per_epoch_losses[0] += pg_loss.detach() # Value loss v_loss = value_loss( newvalue, data["values"][batch_idxes], data["returns"][batch_idxes], args.clip_coef, args.clip_vloss, args.vf_coef, ) per_epoch_losses[1] += v_loss.detach() # Entropy loss ent_loss = entropy_loss(entropy, args.ent_coef) per_epoch_losses[2] += ent_loss.detach() # Overall loss loss = pg_loss + ent_loss + v_loss optimizer.zero_grad(set_to_none=True) loss.backward() nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm) optimizer.step() # Log distributed.reduce(per_epoch_losses, dst=0) if logger is not None: per_epoch_losses = per_epoch_losses / (len(sampler) * distributed.get_world_size()) logger.add_scalar("Loss/policy_loss", per_epoch_losses[0], global_step) logger.add_scalar("Loss/value_loss", per_epoch_losses[1], global_step) logger.add_scalar("Loss/entropy_loss", per_epoch_losses[2], global_step) per_epoch_losses.fill_(0)
null
155,742
from lightning.app import LightningFlow from lightning.app.frontend import StreamlitFrontend from lightning.app.utilities.state import AppState class AppState: _APP_PRIVATE_KEYS: Tuple[str, ...] = ( "_use_localhost", "_host", "_session_id", "_state", "_last_state", "_url", "_port", "_request_state", "_store_state", "_send_state", "_my_affiliation", "_find_state_under_affiliation", "_plugin", "_attach_plugin", "_authorized", "is_authorized", "_debug", "_session", ) _MY_AFFILIATION: Tuple[str, ...] = () def __init__( self, host: Optional[str] = None, port: Optional[int] = None, last_state: Optional[Dict] = None, state: Optional[Dict] = None, my_affiliation: Tuple[str, ...] = None, plugin: Optional[BaseStatePlugin] = None, ) -> None: """The AppState class enables Frontend users to interact with their application state. When the state isn't defined, it would be pulled from the app REST API Server. If the state gets modified by the user, the new state would be sent to the API Server. Arguments: host: Rest API Server current host port: Rest API Server current port last_state: The state pulled on first access. state: The state modified by the user. my_affiliation: A tuple describing the affiliation this app state represents. When storing a state dict on this AppState, this affiliation will be used to reduce the scope of the given state. plugin: A plugin to handle authorization. """ self._use_localhost = "LIGHTNING_APP_STATE_URL" not in os.environ self._host = host or ("http://127.0.0.1" if self._use_localhost else None) self._port = port or (APP_SERVER_PORT if self._use_localhost else None) self._last_state = last_state self._state = state self._session_id = "1234" self._my_affiliation = my_affiliation if my_affiliation is not None else AppState._MY_AFFILIATION self._authorized = None self._attach_plugin(plugin) self._session = self._configure_session() def _url(self) -> str: if self._host is None: app_ip = "" if "LIGHTNING_CLOUD_PROJECT_ID" in os.environ and "LIGHTNING_CLOUD_APP_ID" in os.environ: client = LightningClient() app_instance = client.lightningapp_instance_service_get_lightningapp_instance( os.environ.get("LIGHTNING_CLOUD_PROJECT_ID"), os.environ.get("LIGHTNING_CLOUD_APP_ID"), ) app_ip = app_instance.status.ip_address # TODO: Don't hard code port 8080 here self._host = f"http://{app_ip}:8080" if app_ip else APP_SERVER_HOST return f"{self._host}:{self._port}" if self._use_localhost else self._host def _attach_plugin(self, plugin: Optional[BaseStatePlugin]) -> None: plugin = plugin if plugin is not None else AppStatePlugin() self._plugin = plugin def _find_state_under_affiliation(state, my_affiliation: Tuple[str, ...]) -> Dict[str, Any]: """This method is used to extract the subset of the app state associated with the given affiliation. For example, if the affiliation is ``("root", "subflow")``, then the returned state will be ``state["flows"]["subflow"]``. """ children_state = state for name in my_affiliation: if name in children_state["flows"]: children_state = children_state["flows"][name] elif name in children_state["works"]: children_state = children_state["works"][name] else: raise ValueError(f"Failed to extract the state under the affiliation '{my_affiliation}'.") return children_state def _store_state(self, state: Dict[str, Any]) -> None: # Relying on the global variable to ensure the # deep_diff is done on the entire state. global _LAST_STATE global _STATE _LAST_STATE = deepcopy(state) _STATE = state # If the affiliation is passed, the AppState was created in a LightningFlow context. # The state should be only the one of this LightningFlow and its children. self._last_state = self._find_state_under_affiliation(_LAST_STATE, self._my_affiliation) self._state = self._find_state_under_affiliation(_STATE, self._my_affiliation) def send_delta(self) -> None: app_url = f"{self._url}/api/v1/delta" deep_diff = DeepDiff(_LAST_STATE, _STATE, verbose_level=2) assert self._plugin is not None # TODO: Find how to prevent the infinite loop on refresh without storing the DeepDiff if self._plugin.should_update_app(deep_diff): data = {"delta": json.loads(deep_diff.to_json())} headers = headers_for(self._plugin.get_context()) try: # TODO: Send the delta directly to the REST API. response = self._session.post(app_url, json=data, headers=headers) except ConnectionError as ex: raise AttributeError("Failed to connect and send the app state. Is the app running?") from ex if response and response.status_code != 200: raise Exception(f"The response from the server was {response.status_code}. Your inputs were rejected.") def _request_state(self) -> None: if self._state is not None: return app_url = f"{self._url}/api/v1/state" headers = headers_for(self._plugin.get_context()) if self._plugin else {} response_json = {} # Sometimes the state URL can return an empty JSON when things are being set-up, # so we wait for it to be ready here. while response_json == {}: sleep(0.5) try: response = self._session.get(app_url, headers=headers, timeout=1) except ConnectionError as ex: raise AttributeError("Failed to connect and fetch the app state. Is the app running?") from ex self._authorized = response.status_code if self._authorized != 200: return response_json = response.json() logger.debug(f"GET STATE {response} {response_json}") self._store_state(response_json) def __getattr__(self, name: str) -> Union[Any, "AppState"]: if name in self._APP_PRIVATE_KEYS: return object.__getattr__(self, name) # The state needs to be fetched on access if it doesn't exist. self._request_state() if name in self._state.get("vars", {}): value = self._state["vars"][name] if isinstance(value, dict): return _maybe_create_drive("root." + ".".join(self._my_affiliation), value) return value if name in self._state.get("works", {}): return AppState( self._host, self._port, last_state=self._last_state["works"][name], state=self._state["works"][name] ) if name in self._state.get("flows", {}): return AppState( self._host, self._port, last_state=self._last_state["flows"][name], state=self._state["flows"][name], ) if name in self._state.get("structures", {}): return AppState( self._host, self._port, last_state=self._last_state["structures"][name], state=self._state["structures"][name], ) raise AttributeError( f"Failed to access '{name}' through `AppState`. The state provides:" f" Variables: {list(self._state['vars'].keys())}," f" Components: {list(self._state.get('flows', {}).keys()) + list(self._state.get('works', {}).keys())}", ) def __getitem__(self, key: str): return self.__getattr__(key) def __setattr__(self, name: str, value: Any) -> None: if name in self._APP_PRIVATE_KEYS: object.__setattr__(self, name, value) return # The state needs to be fetched on access if it doesn't exist. self._request_state() # TODO: Find a way to aggregate deltas to avoid making # request for each attribute change. if name in self._state["vars"]: self._state["vars"][name] = value self.send_delta() elif name in self._state["flows"]: raise AttributeError("You shouldn't set the flows directly onto the state. Use its attributes instead.") elif name in self._state["works"]: raise AttributeError("You shouldn't set the works directly onto the state. Use its attributes instead.") else: raise AttributeError( f"Failed to access '{name}' through `AppState`. The state provides:" f" Variables: {list(self._state['vars'].keys())}," f" Components: {list(self._state['flows'].keys()) + list(self._state['works'].keys())}", ) def __repr__(self) -> str: return str(self._state) def __bool__(self) -> bool: return bool(self._state) def __len__(self) -> int: # The state needs to be fetched on access if it doesn't exist. self._request_state() keys = [] for component in ["flows", "works", "structures"]: keys.extend(list(self._state.get(component, {}))) return len(keys) def items(self) -> List[Dict[str, Any]]: # The state needs to be fetched on access if it doesn't exist. self._request_state() items = [] for component in ["flows", "works"]: state = self._state.get(component, {}) last_state = self._last_state.get(component, {}) for name, state_value in state.items(): v = AppState( self._host, self._port, last_state=last_state[name], state=state_value, ) items.append((name, v)) structures = self._state.get("structures", {}) last_structures = self._last_state.get("structures", {}) if structures: for component in ["flows", "works"]: state = structures.get(component, {}) last_state = last_structures.get(component, {}) for name, state_value in state.items(): v = AppState( self._host, self._port, last_state=last_state[name], state=state_value, ) items.append((name, v)) return items def _configure_session() -> Session: return _configure_session() def render_fn(state: AppState): import json import hiplot as hip import streamlit as st from streamlit_autorefresh import st_autorefresh st.set_page_config(layout="wide") st_autorefresh(interval=1000, limit=None, key="refresh") if not state.data: st.write("No data available yet ! Stay tuned") return xp = hip.Experiment.from_iterable(state.data) ret_val = xp.to_streamlit(ret="selected_uids", key="hip").display() st.markdown("hiplot returned " + json.dumps(ret_val))
null
155,743
import os import os.path import tarfile import zipfile import requests The provided code snippet includes necessary dependencies for implementing the `download_data` function. Write a Python function `def download_data(url: str, path: str = "data/", verbose: bool = False) -> None` to solve the following problem: Download file with progressbar. # Code taken from: https://gist.github.com/ruxi/5d6803c116ec1130d484a4ab8c00c603 # __author__ = "github.com/ruxi" # __license__ = "MIT" Usage: download_file('http://web4host.net/5MB.zip') Here is the function: def download_data(url: str, path: str = "data/", verbose: bool = False) -> None: """Download file with progressbar. # Code taken from: https://gist.github.com/ruxi/5d6803c116ec1130d484a4ab8c00c603 # __author__ = "github.com/ruxi" # __license__ = "MIT" Usage: download_file('http://web4host.net/5MB.zip') """ if url == "NEED_TO_BE_CREATED": raise NotImplementedError if not os.path.exists(path): os.makedirs(path) local_filename = os.path.join(path, url.split("/")[-1]) r = requests.get(url, stream=True, verify=False) file_size = int(r.headers["Content-Length"]) if "Content-Length" in r.headers else 0 chunk_size = 1024 num_bars = int(file_size / chunk_size) if verbose: print({"file_size": file_size}) print({"num_bars": num_bars}) if not os.path.exists(local_filename): with open(local_filename, "wb") as fp: for chunk in r.iter_content(chunk_size=chunk_size): fp.write(chunk) # type: ignore def extract_tarfile(file_path: str, extract_path: str, mode: str): if os.path.exists(file_path): with tarfile.open(file_path, mode=mode) as tar_ref: for member in tar_ref.getmembers(): try: tar_ref.extract(member, path=extract_path, set_attrs=False) except PermissionError: raise PermissionError(f"Could not extract tar file {file_path}") if ".zip" in local_filename: if os.path.exists(local_filename): with zipfile.ZipFile(local_filename, "r") as zip_ref: zip_ref.extractall(path) # noqa: S202 elif local_filename.endswith(".tar.gz") or local_filename.endswith(".tgz"): extract_tarfile(local_filename, path, "r:gz") elif local_filename.endswith(".tar.bz2") or local_filename.endswith(".tbz"): extract_tarfile(local_filename, path, "r:bz2")
Download file with progressbar. # Code taken from: https://gist.github.com/ruxi/5d6803c116ec1130d484a4ab8c00c603 # __author__ = "github.com/ruxi" # __license__ = "MIT" Usage: download_file('http://web4host.net/5MB.zip')
155,744
import argparse import os import uvicorn from fastapi import FastAPI from fastapi.requests import Request from fastapi.responses import HTMLResponse async def get_file_content(request: Request, response_class=HTMLResponse): lines = "\n".join(["<p>" + line + "</p>" for line in content]) return HTMLResponse(f"<html><head></head><body><ul>{lines}</ul></body></html>")
null
155,745
from typing import Callable from lightning import LightningApp, LightningFlow from lightning.app.frontend import JustPyFrontend def render_fn(get_state: Callable) -> Callable: import justpy as jp def webpage(): wp = jp.QuasarPage(dark=True) d = jp.Div(classes="q-pa-md q-gutter-sm", a=wp) container = jp.QBtn(color="primary", text="Counter: 0") async def click(*_): state = get_state() state.counter += 1 container.text = f"Counter: {state.counter}" button = jp.QBtn(color="primary", text="Click Me!", click=click) d.add(button) d.add(container) return wp return webpage
null
155,746
import os from importlib import import_module import numpy as np import pandas as pd from lightning.app import LightningApp, LightningFlow, LightningWork from lightning.app.components import TracerPythonScript from lightning.app.storage import Payload from lightning.app.structures import Dict, List from sklearn import datasets from sklearn.metrics import mean_squared_error def get_path(path): return os.path.join(os.path.dirname(__file__), path)
null
155,747
from command import CustomCommand, CustomConfig from lightning import LightningFlow from lightning.app.api import Get, Post from lightning.app.core.app import LightningApp async def handler(): print("Has been called") return "Hello World !"
null
155,748
from lightning.app import LightningApp, LightningFlow from lightning.app.frontend import StreamlitFrontend from lightning.app.utilities.state import AppState class AppState: _APP_PRIVATE_KEYS: Tuple[str, ...] = ( "_use_localhost", "_host", "_session_id", "_state", "_last_state", "_url", "_port", "_request_state", "_store_state", "_send_state", "_my_affiliation", "_find_state_under_affiliation", "_plugin", "_attach_plugin", "_authorized", "is_authorized", "_debug", "_session", ) _MY_AFFILIATION: Tuple[str, ...] = () def __init__( self, host: Optional[str] = None, port: Optional[int] = None, last_state: Optional[Dict] = None, state: Optional[Dict] = None, my_affiliation: Tuple[str, ...] = None, plugin: Optional[BaseStatePlugin] = None, ) -> None: """The AppState class enables Frontend users to interact with their application state. When the state isn't defined, it would be pulled from the app REST API Server. If the state gets modified by the user, the new state would be sent to the API Server. Arguments: host: Rest API Server current host port: Rest API Server current port last_state: The state pulled on first access. state: The state modified by the user. my_affiliation: A tuple describing the affiliation this app state represents. When storing a state dict on this AppState, this affiliation will be used to reduce the scope of the given state. plugin: A plugin to handle authorization. """ self._use_localhost = "LIGHTNING_APP_STATE_URL" not in os.environ self._host = host or ("http://127.0.0.1" if self._use_localhost else None) self._port = port or (APP_SERVER_PORT if self._use_localhost else None) self._last_state = last_state self._state = state self._session_id = "1234" self._my_affiliation = my_affiliation if my_affiliation is not None else AppState._MY_AFFILIATION self._authorized = None self._attach_plugin(plugin) self._session = self._configure_session() def _url(self) -> str: if self._host is None: app_ip = "" if "LIGHTNING_CLOUD_PROJECT_ID" in os.environ and "LIGHTNING_CLOUD_APP_ID" in os.environ: client = LightningClient() app_instance = client.lightningapp_instance_service_get_lightningapp_instance( os.environ.get("LIGHTNING_CLOUD_PROJECT_ID"), os.environ.get("LIGHTNING_CLOUD_APP_ID"), ) app_ip = app_instance.status.ip_address # TODO: Don't hard code port 8080 here self._host = f"http://{app_ip}:8080" if app_ip else APP_SERVER_HOST return f"{self._host}:{self._port}" if self._use_localhost else self._host def _attach_plugin(self, plugin: Optional[BaseStatePlugin]) -> None: plugin = plugin if plugin is not None else AppStatePlugin() self._plugin = plugin def _find_state_under_affiliation(state, my_affiliation: Tuple[str, ...]) -> Dict[str, Any]: """This method is used to extract the subset of the app state associated with the given affiliation. For example, if the affiliation is ``("root", "subflow")``, then the returned state will be ``state["flows"]["subflow"]``. """ children_state = state for name in my_affiliation: if name in children_state["flows"]: children_state = children_state["flows"][name] elif name in children_state["works"]: children_state = children_state["works"][name] else: raise ValueError(f"Failed to extract the state under the affiliation '{my_affiliation}'.") return children_state def _store_state(self, state: Dict[str, Any]) -> None: # Relying on the global variable to ensure the # deep_diff is done on the entire state. global _LAST_STATE global _STATE _LAST_STATE = deepcopy(state) _STATE = state # If the affiliation is passed, the AppState was created in a LightningFlow context. # The state should be only the one of this LightningFlow and its children. self._last_state = self._find_state_under_affiliation(_LAST_STATE, self._my_affiliation) self._state = self._find_state_under_affiliation(_STATE, self._my_affiliation) def send_delta(self) -> None: app_url = f"{self._url}/api/v1/delta" deep_diff = DeepDiff(_LAST_STATE, _STATE, verbose_level=2) assert self._plugin is not None # TODO: Find how to prevent the infinite loop on refresh without storing the DeepDiff if self._plugin.should_update_app(deep_diff): data = {"delta": json.loads(deep_diff.to_json())} headers = headers_for(self._plugin.get_context()) try: # TODO: Send the delta directly to the REST API. response = self._session.post(app_url, json=data, headers=headers) except ConnectionError as ex: raise AttributeError("Failed to connect and send the app state. Is the app running?") from ex if response and response.status_code != 200: raise Exception(f"The response from the server was {response.status_code}. Your inputs were rejected.") def _request_state(self) -> None: if self._state is not None: return app_url = f"{self._url}/api/v1/state" headers = headers_for(self._plugin.get_context()) if self._plugin else {} response_json = {} # Sometimes the state URL can return an empty JSON when things are being set-up, # so we wait for it to be ready here. while response_json == {}: sleep(0.5) try: response = self._session.get(app_url, headers=headers, timeout=1) except ConnectionError as ex: raise AttributeError("Failed to connect and fetch the app state. Is the app running?") from ex self._authorized = response.status_code if self._authorized != 200: return response_json = response.json() logger.debug(f"GET STATE {response} {response_json}") self._store_state(response_json) def __getattr__(self, name: str) -> Union[Any, "AppState"]: if name in self._APP_PRIVATE_KEYS: return object.__getattr__(self, name) # The state needs to be fetched on access if it doesn't exist. self._request_state() if name in self._state.get("vars", {}): value = self._state["vars"][name] if isinstance(value, dict): return _maybe_create_drive("root." + ".".join(self._my_affiliation), value) return value if name in self._state.get("works", {}): return AppState( self._host, self._port, last_state=self._last_state["works"][name], state=self._state["works"][name] ) if name in self._state.get("flows", {}): return AppState( self._host, self._port, last_state=self._last_state["flows"][name], state=self._state["flows"][name], ) if name in self._state.get("structures", {}): return AppState( self._host, self._port, last_state=self._last_state["structures"][name], state=self._state["structures"][name], ) raise AttributeError( f"Failed to access '{name}' through `AppState`. The state provides:" f" Variables: {list(self._state['vars'].keys())}," f" Components: {list(self._state.get('flows', {}).keys()) + list(self._state.get('works', {}).keys())}", ) def __getitem__(self, key: str): return self.__getattr__(key) def __setattr__(self, name: str, value: Any) -> None: if name in self._APP_PRIVATE_KEYS: object.__setattr__(self, name, value) return # The state needs to be fetched on access if it doesn't exist. self._request_state() # TODO: Find a way to aggregate deltas to avoid making # request for each attribute change. if name in self._state["vars"]: self._state["vars"][name] = value self.send_delta() elif name in self._state["flows"]: raise AttributeError("You shouldn't set the flows directly onto the state. Use its attributes instead.") elif name in self._state["works"]: raise AttributeError("You shouldn't set the works directly onto the state. Use its attributes instead.") else: raise AttributeError( f"Failed to access '{name}' through `AppState`. The state provides:" f" Variables: {list(self._state['vars'].keys())}," f" Components: {list(self._state['flows'].keys()) + list(self._state['works'].keys())}", ) def __repr__(self) -> str: return str(self._state) def __bool__(self) -> bool: return bool(self._state) def __len__(self) -> int: # The state needs to be fetched on access if it doesn't exist. self._request_state() keys = [] for component in ["flows", "works", "structures"]: keys.extend(list(self._state.get(component, {}))) return len(keys) def items(self) -> List[Dict[str, Any]]: # The state needs to be fetched on access if it doesn't exist. self._request_state() items = [] for component in ["flows", "works"]: state = self._state.get(component, {}) last_state = self._last_state.get(component, {}) for name, state_value in state.items(): v = AppState( self._host, self._port, last_state=last_state[name], state=state_value, ) items.append((name, v)) structures = self._state.get("structures", {}) last_structures = self._last_state.get("structures", {}) if structures: for component in ["flows", "works"]: state = structures.get(component, {}) last_state = last_structures.get(component, {}) for name, state_value in state.items(): v = AppState( self._host, self._port, last_state=last_state[name], state=state_value, ) items.append((name, v)) return items def _configure_session() -> Session: return _configure_session() def render_fn(state: AppState): import streamlit as st should_print = st.button("Should print to the terminal ?") if should_print: state.should_print = not state.should_print st.write("Currently printing." if state.should_print else "Currently waiting to print.")
null
155,749
import torch from lightning.app import CloudCompute, LightningApp, LightningWork from lightning.app.components import MultiNode from torch.nn.parallel.distributed import DistributedDataParallel def distributed_train(local_rank: int, main_address: str, main_port: int, num_nodes: int, node_rank: int, nprocs: int): # 1. SET UP DISTRIBUTED ENVIRONMENT global_rank = local_rank + node_rank * nprocs world_size = num_nodes * nprocs if torch.distributed.is_available() and not torch.distributed.is_initialized(): torch.distributed.init_process_group( "nccl" if torch.cuda.is_available() else "gloo", rank=global_rank, world_size=world_size, init_method=f"tcp://{main_address}:{main_port}", ) # 2. PREPARE DISTRIBUTED MODEL model = torch.nn.Linear(32, 2) device = torch.device(f"cuda:{local_rank}") if torch.cuda.is_available() else torch.device("cpu") model = DistributedDataParallel(model, device_ids=[local_rank] if torch.cuda.is_available() else None).to(device) # 3. SETUP LOSS AND OPTIMIZER criterion = torch.nn.MSELoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # 4.TRAIN THE MODEL FOR 50 STEPS for step in range(50): model.zero_grad() x = torch.randn(64, 32).to(device) output = model(x) loss = criterion(output, torch.ones_like(output)) print(f"global_rank: {global_rank} step: {step} loss: {loss}") loss.backward() optimizer.step() # 5. VERIFY ALL COPIES OF THE MODEL HAVE THE SAME WEIGTHS AT END OF TRAINING weight = model.module.weight.clone() torch.distributed.all_reduce(weight) assert torch.equal(model.module.weight, weight / world_size) print("Multi Node Distributed Training Done!")
null
155,750
import os from time import sleep from lightning.app import LightningApp, LightningFlow from lightning.app.frontend import StaticWebFrontend, StreamlitFrontend def render_c11(state): import streamlit as st st.write(state.message)
null
155,751
import os import sys import requests import html import hashlib import PIL.Image import PIL.ImageFile import numpy as np import scipy.ndimage import threading import queue import time import json import uuid import glob import argparse import itertools import shutil from collections import OrderedDict, defaultdict def run(tasks, **download_kwargs): def run_cmdline(argv): parser = argparse.ArgumentParser(prog=argv[0], description='Download Flickr-Face-HQ (FFHQ) dataset to current working directory.') parser.add_argument('-j', '--json', help='download metadata as JSON (254 MB)', dest='tasks', action='append_const', const='json') parser.add_argument('-s', '--stats', help='print statistics about the dataset', dest='tasks', action='append_const', const='stats') parser.add_argument('-i', '--images', help='download 1024x1024 images as PNG (89.1 GB)', dest='tasks', action='append_const', const='images') parser.add_argument('-t', '--thumbs', help='download 128x128 thumbnails as PNG (1.95 GB)', dest='tasks', action='append_const', const='thumbs') parser.add_argument('-w', '--wilds', help='download in-the-wild images as PNG (955 GB)', dest='tasks', action='append_const', const='wilds') parser.add_argument('-r', '--tfrecords', help='download multi-resolution TFRecords (273 GB)', dest='tasks', action='append_const', const='tfrecords') parser.add_argument('-a', '--align', help='recreate 1024x1024 images from in-the-wild images', dest='tasks', action='append_const', const='align') parser.add_argument('--num_threads', help='number of concurrent download threads (default: 32)', type=int, default=32, metavar='NUM') parser.add_argument('--status_delay', help='time between download status prints (default: 0.2)', type=float, default=0.2, metavar='SEC') parser.add_argument('--timing_window', help='samples for estimating download eta (default: 50)', type=int, default=50, metavar='LEN') parser.add_argument('--chunk_size', help='chunk size for each download thread (default: 128)', type=int, default=128, metavar='KB') parser.add_argument('--num_attempts', help='number of download attempts per file (default: 10)', type=int, default=10, metavar='NUM') parser.add_argument('--random-shift', help='standard deviation of random crop rectangle jitter', type=float, default=0.0, metavar='SHIFT') parser.add_argument('--retry-crops', help='retry random shift if crop rectangle falls outside image (up to 1000 times)', dest='retry_crops', default=False, action='store_true') parser.add_argument('--no-rotation', help='keep the original orientation of images', dest='no_rotation', default=False, action='store_true') parser.add_argument('--no-padding', help='do not apply blur-padding outside and near the image borders', dest='no_padding', default=False, action='store_true') parser.add_argument('--source-dir', help='where to find already downloaded FFHQ source data', default='', metavar='DIR') args = parser.parse_args() if not args.tasks: print('No tasks specified. Please see "-h" for help.') exit(1) run(**vars(args))
null
155,752
import gradio as gr import time from transformers import AutoTokenizer, AutoModelForCausalLM,TextIteratorStreamer from threading import Thread import torch,sys,os import json import pandas import argparse def user(user_message, history): return "", history + [[user_message, None]]
null
155,753
import gradio as gr import time from transformers import AutoTokenizer, AutoModelForCausalLM,TextIteratorStreamer from threading import Thread import torch,sys,os import json import pandas import argparse def bot(history,temperature,top_p,slider_context_times): if pandas.isnull(history[-1][1])==False: history[-1][1] = None yield history slider_context_times = int(slider_context_times) history_true = history[1:-1] prompt = '' if slider_context_times>0: prompt += '\n'.join([("<s>Human: "+one_chat[0].replace('<br>','\n')+'\n</s>' if one_chat[0] else '') +"<s>Assistant: "+one_chat[1].replace('<br>','\n')+'\n</s>' for one_chat in history_true[-slider_context_times:] ]) prompt += "<s>Human: "+history[-1][0].replace('<br>','\n')+"\n</s><s>Assistant:" input_ids = tokenizer([prompt], return_tensors="pt",add_special_tokens=False).input_ids[:,-512:].to('cuda') generate_input = { "input_ids":input_ids, "max_new_tokens":512, "do_sample":True, "top_k":50, "top_p":top_p, "temperature":temperature, "repetition_penalty":1.3, "streamer":streamer, "eos_token_id":tokenizer.eos_token_id, "bos_token_id":tokenizer.bos_token_id, "pad_token_id":tokenizer.pad_token_id } thread = Thread(target=model.generate, kwargs=generate_input) thread.start() start_time = time.time() bot_message ='' print('Human:',history[-1][0]) print('Assistant: ',end='',flush=True) for new_text in streamer: print(new_text,end='',flush=True) if len(new_text)==0: continue if new_text!='</s>': bot_message+=new_text if 'Human:' in bot_message: bot_message = bot_message.split('Human:')[0] history[-1][1] = bot_message yield history end_time =time.time() print() print('生成耗时:',end_time-start_time,'文字长度:',len(bot_message),'字耗时:',(end_time-start_time)/len(bot_message))
null
155,754
import gradio as gr import time from transformers import AutoTokenizer, AutoModelForCausalLM,TextIteratorStreamer from threading import Thread from peft import PeftModel,PeftConfig import torch,sys,os import json import pandas import argparse def user(user_message, history): return "", history + [[user_message, None]]
null
155,755
import gradio as gr import time from transformers import AutoTokenizer, AutoModelForCausalLM,TextIteratorStreamer from threading import Thread from peft import PeftModel,PeftConfig import torch,sys,os import json import pandas import argparse def bot(history,temperature,top_p,slider_context_times): if pandas.isnull(history[-1][1])==False: history[-1][1] = None yield history slider_context_times = int(slider_context_times) history_true = history[1:-1] prompt = '' if slider_context_times>0: prompt += '\n'.join([("<s>Human: "+one_chat[0].replace('<br>','\n')+'\n</s>' if one_chat[0] else '') +"<s>Assistant: "+one_chat[1].replace('<br>','\n')+'\n</s>' for one_chat in history_true[-slider_context_times:] ]) prompt += "<s>Human: "+history[-1][0].replace('<br>','\n')+"\n</s><s>Assistant:" input_ids = tokenizer([prompt], return_tensors="pt",add_special_tokens=False).input_ids[:,-512:].to('cuda') generate_input = { "input_ids":input_ids, "max_new_tokens":512, "do_sample":True, "top_k":50, "top_p":top_p, "temperature":temperature, "repetition_penalty":1.3, "streamer":streamer, "eos_token_id":tokenizer.eos_token_id, "bos_token_id":tokenizer.bos_token_id, "pad_token_id":tokenizer.pad_token_id } thread = Thread(target=model.generate, kwargs=generate_input) thread.start() start_time = time.time() bot_message ='' print('Human:',history[-1][0]) print('Assistant: ',end='',flush=True) for new_text in streamer: print(new_text,end='',flush=True) if len(new_text)==0: continue if new_text!='</s>': bot_message+=new_text if 'Human:' in bot_message: bot_message = bot_message.split('Human:')[0] history[-1][1] = bot_message yield history end_time =time.time() print() print('生成耗时:',end_time-start_time,'文字长度:',len(bot_message),'字耗时:',(end_time-start_time)/len(bot_message))
null
155,756
import logging import math import os import sys from dataclasses import dataclass, field from torchdata.datapipes.iter import IterDataPipe, IterableWrapper from itertools import chain import deepspeed from typing import Optional,List import datasets import pandas as pd import evaluate import torch from datasets import load_dataset from datasets.combine import interleave_datasets import transformers from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR from transformers import ( CONFIG_MAPPING, MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoModelForCausalLM, AutoTokenizer, TrainerCallback, TrainerState, TrainerControl, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, is_torch_tpu_available, set_seed, ) import datetime from transformers.testing_utils import CaptureLogger from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version from datasets import interleave_datasets def main(): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_clm", model_args, data_args) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)], ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() log_level = training_args.get_process_log_level() logger.setLevel(log_level) datasets.utils.logging.set_verbosity(log_level) transformers.utils.logging.set_verbosity(log_level) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" ) logger.info(f"Training/evaluation parameters {training_args}") # Detecting last checkpoint. last_checkpoint = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if True: data_files = {} dataset_args = {} if data_args.train_files is not None: print(data_args.train_files) data_files["train"] = data_args.train_files print('训练文件总个数',len(data_args.train_files)) if data_args.validation_files is not None: data_files["validation"] = data_args.validation_files extension = ( data_files["train"][0].split(".")[-1] if data_files["train"] is not None else data_args.validation_files.split(".")[-1] ) if extension == "txt": extension = "text" dataset_args["keep_linebreaks"] = data_args.keep_linebreaks raw_datasets = load_dataset( extension, data_files=data_files, streaming=data_args.streaming, cache_dir=os.path.join(training_args.output_dir,'dataset_cache'), use_auth_token=True if model_args.use_auth_token else None, **dataset_args, ) if data_args.streaming: raw_datasets = raw_datasets.shuffle(seed=training_args.seed, buffer_size=1000000) # If no validation data is there, validation_split_percentage will be used to divide the dataset. if "validation" not in raw_datasets.keys(): raw_datasets["validation"] = load_dataset( extension, data_files=data_files, split=f"train[:{data_args.validation_split_percentage}%]", cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, **dataset_args, ) raw_datasets["train"] = load_dataset( extension, data_files=data_files, split=f"train[{data_args.validation_split_percentage}%:]", cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, **dataset_args, ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. config_kwargs = { "cache_dir": model_args.cache_dir, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.config_name: config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs) elif model_args.model_name_or_path: config = AutoConfig.from_pretrained(model_args.model_name_or_path, **config_kwargs) else: config = CONFIG_MAPPING[model_args.model_type]() logger.warning("You are instantiating a new config instance from scratch.") if model_args.config_overrides is not None: logger.info(f"Overriding config: {model_args.config_overrides}") config.update_from_string(model_args.config_overrides) logger.info(f"New config: {config}") print(training_args.local_rank,'start load tokenizer') tokenizer_kwargs = { "cache_dir": model_args.cache_dir, "use_fast": model_args.use_fast_tokenizer, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.tokenizer_name: tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, **tokenizer_kwargs) elif model_args.model_name_or_path: tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, **tokenizer_kwargs) else: raise ValueError( "You are instantiating a new tokenizer from scratch. This is not supported by this script." "You can do it from another script, save it, and load it from here, using --tokenizer_name." ) print(training_args.local_rank,'end load tokenizer') print(training_args.local_rank,'start load model') if model_args.model_name_or_path: torch_dtype = ( model_args.torch_dtype if model_args.torch_dtype in ["auto", None] else getattr(torch, model_args.torch_dtype) ) model = AutoModelForCausalLM.from_pretrained( model_args.model_name_or_path, from_tf=bool(".ckpt" in model_args.model_name_or_path), config=config, cache_dir=model_args.cache_dir, revision=model_args.model_revision, trust_remote_code=True, use_flash_attention_2=True, use_auth_token=True if model_args.use_auth_token else None, ) else: model = AutoModelForCausalLM.from_config(config) n_params = sum({p.data_ptr(): p.numel() for p in model.parameters()}.values()) logger.info(f"Training new model from scratch - Total size={n_params/2**20:.2f}M params") print(training_args.local_rank,'end load model') # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch # on a small vocab and want a smaller embedding size, remove this test. embedding_size = model.get_input_embeddings().weight.shape[0] if len(tokenizer) > embedding_size: model.resize_token_embeddings(len(tokenizer)) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: if data_args.streaming: dataset_head = raw_datasets["train"].take(3) print(list(dataset_head)) column_names = list(list(dataset_head)[0].keys()) else: column_names = list(raw_datasets["train"].features) else: if data_args.streaming: dataset_head = raw_datasets["validation"].take(3) column_names = list(list(dataset_head)[0].keys()) else: column_names = list(raw_datasets["validation"].features) print(column_names) text_column_name = "text" if "text" in column_names else column_names[0] # since this will be pickled to avoid _LazyModule error in Hasher force logger loading before tokenize_function tok_logger = transformers.utils.logging.get_logger("transformers.tokenization_utils_base") def tokenize_function(examples): with CaptureLogger(tok_logger) as cl: output = tokenizer( [ '<s>'+item+'</s>' for item in examples[text_column_name]]) return output with training_args.main_process_first(desc="dataset map tokenization"): if not data_args.streaming: tokenized_datasets = raw_datasets.map( tokenize_function, batched=True, num_proc=data_args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on dataset", ) else: tokenized_datasets = raw_datasets.map( tokenize_function, batched=True, remove_columns=column_names, batch_size = 60000, ) if data_args.block_size is None: block_size = tokenizer.model_max_length if block_size > 1024: logger.warning( "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value" " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can" " override this default with `--block_size xxx`." ) block_size = 1024 else: if data_args.block_size > tokenizer.model_max_length: logger.warning( f"The block_size passed ({data_args.block_size}) is larger than the maximum length for the model" f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}." ) block_size = min(data_args.block_size, tokenizer.model_max_length) # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size. def group_texts(examples): # Concatenate all texts. concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()} # concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()} total_length = len(concatenated_examples[list(examples.keys())[0]]) # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can # customize this part to your needs. if total_length >= block_size: total_length = (total_length // block_size) * block_size # Split by chunks of max_len. result = { k: [t[i : i + block_size] for i in range(0, total_length, block_size)] for k, t in concatenated_examples.items() } # print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) logger.info("group texts input examples length%d after_group size%d"%(len(examples['input_ids']),len(result["input_ids"]))) result["labels"] = result["input_ids"].copy() return result # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower # to preprocess. # # To speed up this part, we use multiprocessing. See the documentation of the map method for more information: # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map with training_args.main_process_first(desc="grouping texts together"): if not data_args.streaming: lm_datasets = tokenized_datasets.map( group_texts, batched=True, num_proc=data_args.preprocessing_num_workers, load_from_cache_file=not data_args.overwrite_cache, desc=f"Grouping texts in chunks of {block_size}", batch_size = 40000, ) else: lm_datasets = tokenized_datasets.map( group_texts, batched=True, batch_size = 60000, ) print(training_args.local_rank,'start select train_dataset') if training_args.do_train: if "train" not in tokenized_datasets: raise ValueError("--do_train requires a train dataset") train_dataset = lm_datasets["train"] if data_args.max_train_samples is not None and data_args.streaming==False: max_train_samples = min(len(train_dataset), data_args.max_train_samples) train_dataset = train_dataset.select(range(max_train_samples)) print(training_args.local_rank,'end select train_dataset') if training_args.do_eval: if "validation" not in tokenized_datasets: raise ValueError("--do_eval requires a validation dataset") print(training_args.local_rank,'start select eval_dataset') eval_dataset = lm_datasets["validation"] if data_args.max_eval_samples is not None and data_args.streaming==False : max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples) eval_dataset = eval_dataset.select(range(max_eval_samples)) print(training_args.local_rank,'end select eval_dataset') def preprocess_logits_for_metrics(logits, labels): if isinstance(logits, tuple): # Depending on the model and config, logits may contain extra tensors, # like past_key_values, but logits always come first logits = logits[0] return logits.argmax(dim=-1) print(training_args.local_rank,'start load metric') metric = evaluate.load("accuracy.py") print(training_args.local_rank,'end load metric') def compute_metrics(eval_preds): preds, labels = eval_preds # preds have the same shape as the labels, after the argmax(-1) has been calculated # by preprocess_logits_for_metrics but we need to shift the labels labels = labels[:, 1:].reshape(-1) preds = preds[:, :-1].reshape(-1) return metric.compute(predictions=preds, references=labels) print(training_args.local_rank,'Initialize our Trainer') trainer = Trainer( model=model, args=training_args, train_dataset= IterableWrapper(train_dataset) if training_args.do_train else None, eval_dataset= IterableWrapper(eval_dataset) if training_args.do_eval else None, tokenizer=tokenizer, # Data collator will default to DataCollatorWithPadding, so we change it. data_collator=default_data_collator, compute_metrics=compute_metrics if training_args.do_eval and not is_torch_tpu_available() else None, preprocess_logits_for_metrics=preprocess_logits_for_metrics if training_args.do_eval and not is_torch_tpu_available()else None, # callbacks=([SavePeftModelCallback] if isinstance(model, PeftModel) else None), ) if training_args.do_train: checkpoint = None if training_args.resume_from_checkpoint is not None: checkpoint = training_args.resume_from_checkpoint elif last_checkpoint is not None: checkpoint = last_checkpoint print(training_args.local_rank,'start train') train_result = trainer.train(resume_from_checkpoint=checkpoint) trainer.save_model() # Saves the tokenizer too for easy upload metrics = train_result.metrics max_train_samples = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset) ) metrics["train_samples"] = min(max_train_samples, len(train_dataset)) trainer.log_metrics("train", metrics) trainer.save_metrics("train", metrics) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***") metrics = trainer.evaluate() max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset) metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) try: perplexity = math.exp(metrics["eval_loss"]) except OverflowError: perplexity = float("inf") metrics["perplexity"] = perplexity trainer.log_metrics("eval", metrics) trainer.save_metrics("eval", metrics) def _mp_fn(index): # For xla_spawn (TPUs) main()
null
155,757
import logging import math import os import sys import random from dataclasses import dataclass, field from itertools import chain import deepspeed from typing import Optional,List,Union import datasets import evaluate import torch from datasets import load_dataset from peft import ( # noqa: E402 LoraConfig, PeftModel, get_peft_model, get_peft_model_state_dict, prepare_model_for_int8_training, prepare_model_for_kbit_training, set_peft_model_state_dict, ) import transformers from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR from transformers import ( CONFIG_MAPPING, MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoModelForCausalLM, AutoTokenizer, TrainerCallback, TrainerState, TrainerControl, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, BitsAndBytesConfig, is_torch_tpu_available, set_seed, ) from transformers.testing_utils import CaptureLogger from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version import pdb def main(): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) # pdb.set_trace() if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_clm", model_args, data_args) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)], ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() log_level = training_args.get_process_log_level() logger.setLevel(log_level) datasets.utils.logging.set_verbosity(log_level) transformers.utils.logging.set_verbosity(log_level) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" ) logger.info(f"Training/evaluation parameters {training_args}") # Detecting last checkpoint. last_checkpoint = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if True: data_files = {} dataset_args = {} if data_args.train_files is not None: data_files["train"] = data_args.train_files if data_args.validation_files is not None: data_files["validation"] = data_args.validation_files extension = ( data_args.train_files[0].split(".")[-1] if data_args.train_files is not None else data_args.validation_files.split(".")[-1] ) if extension == "txt": extension = "text" dataset_args["keep_linebreaks"] = data_args.keep_linebreaks raw_datasets = load_dataset( extension, data_files=data_files, cache_dir=os.path.join(training_args.output_dir,'dataset_cache'), use_auth_token=True if model_args.use_auth_token else None, **dataset_args, ) # If no validation data is there, validation_split_percentage will be used to divide the dataset. if "validation" not in raw_datasets.keys(): raw_datasets["validation"] = load_dataset( extension, data_files=data_files, split=f"train[:{data_args.validation_split_percentage}%]", cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, **dataset_args, ) raw_datasets["train"] = load_dataset( extension, data_files=data_files, split=f"train[{data_args.validation_split_percentage}%:]", cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, **dataset_args, ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. config_kwargs = { "cache_dir": model_args.cache_dir, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.config_name: config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs) elif model_args.model_name_or_path: config = AutoConfig.from_pretrained(model_args.model_name_or_path, **config_kwargs) else: config = CONFIG_MAPPING[model_args.model_type]() logger.warning("You are instantiating a new config instance from scratch.") if model_args.config_overrides is not None: logger.info(f"Overriding config: {model_args.config_overrides}") config.update_from_string(model_args.config_overrides) logger.info(f"New config: {config}") tokenizer_kwargs = { "cache_dir": model_args.cache_dir, "use_fast": model_args.use_fast_tokenizer, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, "padding_side":'left' } if model_args.tokenizer_name: tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, **tokenizer_kwargs) elif model_args.model_name_or_path: tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, **tokenizer_kwargs) else: raise ValueError( "You are instantiating a new tokenizer from scratch. This is not supported by this script." "You can do it from another script, save it, and load it from here, using --tokenizer_name." ) tokenizer.pad_token = tokenizer.eos_token lora_config = LoraConfig( r=model_args.lora_r, lora_alpha=model_args.lora_alpha, # target_modules=["query_key_value"], # target_modules = ['q_proj', 'k_proj', 'v_proj', 'o_proj'], target_modules = model_args.target_modules, fan_in_fan_out = False, lora_dropout=0.05, inference_mode=False, bias="none", task_type="CAUSAL_LM", ) print(lora_config) bnb_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16 ) if model_args.model_name_or_path: torch_dtype = ( model_args.torch_dtype if model_args.torch_dtype in ["auto", None] else getattr(torch, model_args.torch_dtype) ) print(torch_dtype) torch_dtype = torch.float16 model = AutoModelForCausalLM.from_pretrained( model_args.model_name_or_path, from_tf=bool(".ckpt" in model_args.model_name_or_path), config=config, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, torch_dtype=torch_dtype, load_in_8bit=True if model_args.load_in_bits==8 else False, trust_remote_code=True, use_flash_attention_2=True, quantization_config=bnb_config if model_args.load_in_bits==4 else None, # device_map = 'auto' device_map={"": int(os.environ.get("LOCAL_RANK") or 0)} ) # model = prepare_model_for_int8_training(model, output_embedding_layer_name="embed_out", layer_norm_names=[]) else: model = AutoModelForCausalLM.from_config(config) n_params = sum({p.data_ptr(): p.numel() for p in model.parameters()}.values()) logger.info(f"Training new model from scratch - Total size={n_params/2**20:.2f}M params") # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch # on a small vocab and want a smaller embedding size, remove this test. embedding_size = model.get_input_embeddings().weight.shape[0] if len(tokenizer) > embedding_size: model.resize_token_embeddings(len(tokenizer)) if model_args.load_in_bits==8: model = prepare_model_for_int8_training(model) elif model_args.load_in_bits==4: model = prepare_model_for_kbit_training(model) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: column_names = list(raw_datasets["train"].features) else: column_names = list(raw_datasets["validation"].features) train_on_inputs = True if len(column_names)==1: text_column_name = "text" if "text" in column_names else column_names[0] elif len(column_names)==2: input_column_name = 'input' if 'input' in column_names else column_names[0] target_column_name = 'target' if 'target' in column_names else column_names[0] train_on_inputs=False else: raise ValueError('输入文件列数不对') print('train_on_inputs',train_on_inputs) # since this will be pickled to avoid _LazyModule error in Hasher force logger loading before tokenize_function tok_logger = transformers.utils.logging.get_logger("transformers.tokenization_utils_base") def tokenize_function(examples): with CaptureLogger(tok_logger) as cl: output = tokenizer([ item for item in examples[text_column_name]],truncation=True,max_length=data_args.block_size,padding=False,return_tensors=None) output['labels'] = output['input_ids'].copy() return output def tokenize(prompt): result = tokenizer(prompt,truncation=True,max_length=data_args.block_size,padding=False,return_tensors=None) result["labels"] = result["input_ids"].copy() return result def generate_and_tokenize_prompt(data_point): input_text = data_point[input_column_name] target_text = data_point[target_column_name] full_prompt = input_text+target_text tokenized_full_prompt = tokenize(full_prompt) if not train_on_inputs: user_prompt = input_text tokenized_user_prompt = tokenize(user_prompt) user_prompt_len = len(tokenized_user_prompt["input_ids"]) tokenized_full_prompt["labels"] = [ -100 ] * user_prompt_len + tokenized_full_prompt["labels"][ user_prompt_len: ] return tokenized_full_prompt with training_args.main_process_first(desc="dataset map tokenization"): if not data_args.streaming: tokenized_datasets = raw_datasets.map( tokenize_function if train_on_inputs==True else generate_and_tokenize_prompt, batched=True if train_on_inputs==True else False, num_proc=data_args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on dataset", ) else: tokenized_datasets = raw_datasets.map( tokenize_function if train_on_inputs==True else generate_and_tokenize_prompt, batched=True if train_on_inputs==True else False, remove_columns=column_names, ) if data_args.block_size is None: block_size = tokenizer.model_max_length if block_size > 2048: block_size = 2048 else: block_size = min(data_args.block_size, tokenizer.model_max_length) if training_args.do_train: if "train" not in tokenized_datasets: raise ValueError("--do_train requires a train dataset") train_dataset = tokenized_datasets["train"] if data_args.max_train_samples is not None: max_train_samples = min(len(train_dataset), data_args.max_train_samples) train_dataset = train_dataset.select(range(max_train_samples)) for index in random.sample(range(len(train_dataset)), 3): logger.info(f"Sample {index} of the training set: {train_dataset[index]}.") train_dataset = train_dataset.shuffle(seed=training_args.seed) if training_args.do_eval: if "validation" not in tokenized_datasets: raise ValueError("--do_eval requires a validation dataset") eval_dataset = tokenized_datasets["validation"] if data_args.max_eval_samples is not None: max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples) eval_dataset = eval_dataset.select(range(max_eval_samples)) def preprocess_logits_for_metrics(logits, labels): if isinstance(logits, tuple): # Depending on the model and config, logits may contain extra tensors, # like past_key_values, but logits always come first logits = logits[0] return logits.argmax(dim=-1) metric = evaluate.load("accuracy.py") def compute_metrics(eval_preds): preds, labels = eval_preds # preds have the same shape as the labels, after the argmax(-1) has been calculated # by preprocess_logits_for_metrics but we need to shift the labels labels = labels[:, 1:].reshape(-1) # .reshape(-1) preds = preds[:, :-1].reshape(-1) # .reshape(-1) # print(labels.shape) # true_predictions = [ # [p for (p, l) in zip(pred, gold_label) if l != -100] # for pred, gold_label in zip(preds, labels) # ] # true_labels = [ # [l for (p, l) in zip(pred, gold_label) if l != -100] # for pred, gold_label in zip(preds, labels) # ] # preds = np.array(true_predictions).reshape(-1) # labels = np.array(true_labels).reshape(-1) return metric.compute(predictions=preds, references=labels) # layer_norm_names=[] model = get_peft_model(model, lora_config) model.print_trainable_parameters() # Initialize our Trainer trainer = Trainer( model=model, args=training_args, train_dataset=train_dataset if training_args.do_train else None, eval_dataset=eval_dataset if training_args.do_eval else None, tokenizer=tokenizer, # Data collator will default to DataCollatorWithPadding, so we change it. data_collator=transformers.DataCollatorForSeq2Seq( tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True ), compute_metrics=compute_metrics if training_args.do_eval and not is_torch_tpu_available() else None, preprocess_logits_for_metrics=preprocess_logits_for_metrics if training_args.do_eval and not is_torch_tpu_available()else None, callbacks=([SavePeftModelCallback] if isinstance(model, PeftModel) else None), ) # Training if training_args.do_train: checkpoint = None if training_args.resume_from_checkpoint is not None: resume_from_checkpoint = training_args.resume_from_checkpoint checkpoint_name = os.path.join(resume_from_checkpoint, "pytorch_model.bin") if not os.path.exists(checkpoint_name): checkpoint_name = os.path.join( resume_from_checkpoint, "adapter_model.bin" ) # only LoRA model - LoRA config above has to fit resume_from_checkpoint = ( False # So the trainer won't try loading its state ) # The two files above have a different name depending on how they were saved, but are actually the same. if os.path.exists(checkpoint_name): print(f"Restarting from {checkpoint_name}") adapters_weights = torch.load(checkpoint_name) set_peft_model_state_dict(model, adapters_weights) else: print(f"Checkpoint {checkpoint_name} not found") # checkpoint = Fa elif last_checkpoint is not None: checkpoint = last_checkpoint if torch.__version__ >= "2" and sys.platform != "win32": model = torch.compile(model) train_result = trainer.train(resume_from_checkpoint=checkpoint) trainer.save_model() # Saves the tokenizer too for easy upload metrics = train_result.metrics max_train_samples = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset) ) metrics["train_samples"] = min(max_train_samples, len(train_dataset)) trainer.log_metrics("train", metrics) trainer.save_metrics("train", metrics) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***") metrics = trainer.evaluate() max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset) metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) try: perplexity = math.exp(metrics["eval_loss"]) except OverflowError: perplexity = float("inf") metrics["perplexity"] = perplexity trainer.log_metrics("eval", metrics) trainer.save_metrics("eval", metrics) def _mp_fn(index): # For xla_spawn (TPUs) main()
null
155,758
import logging import math import os import sys import random from dataclasses import dataclass, field from itertools import chain import deepspeed from typing import Optional,List,Union import datasets import evaluate import torch from datasets import load_dataset from peft import ( # noqa: E402 LoraConfig, PeftModel, get_peft_model, get_peft_model_state_dict, prepare_model_for_int8_training, prepare_model_for_kbit_training, set_peft_model_state_dict, ) import transformers from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR from transformers import ( CONFIG_MAPPING, MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoModelForCausalLM, AutoTokenizer, TrainerCallback, TrainerState, TrainerControl, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, BitsAndBytesConfig, is_torch_tpu_available, set_seed, ) from transformers.testing_utils import CaptureLogger from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version import pdb def main(): def _mp_fn(index): # For xla_spawn (TPUs) main()
null
155,759
import argparse import json from typing import AsyncGenerator from fastapi import BackgroundTasks, FastAPI, Request from fastapi.responses import JSONResponse, Response, StreamingResponse import uvicorn from vllm.engine.arg_utils import AsyncEngineArgs from vllm.engine.async_llm_engine import AsyncLLMEngine from vllm.sampling_params import SamplingParams from vllm.utils import random_uuid The provided code snippet includes necessary dependencies for implementing the `generate` function. Write a Python function `async def generate(request: Request) -> Response` to solve the following problem: Generate completion for the request. The request should be a JSON object with the following fields: - prompt: the prompt to use for the generation. - stream: whether to stream the results or not. - other fields: the sampling parameters (See `SamplingParams` for details). Here is the function: async def generate(request: Request) -> Response: """Generate completion for the request. The request should be a JSON object with the following fields: - prompt: the prompt to use for the generation. - stream: whether to stream the results or not. - other fields: the sampling parameters (See `SamplingParams` for details). """ request_dict = await request.json() prompt = request_dict.pop("prompt") stream = request_dict.pop("stream", False) sampling_params = SamplingParams(**request_dict) request_id = random_uuid() results_generator = engine.generate(prompt, sampling_params, request_id) # Streaming case async def stream_results() -> AsyncGenerator[bytes, None]: async for request_output in results_generator: prompt = request_output.prompt text_outputs = [ prompt + output.text for output in request_output.outputs ] ret = {"text": text_outputs} yield (json.dumps(ret) + "\0").encode("utf-8") async def abort_request() -> None: await engine.abort(request_id) if stream: background_tasks = BackgroundTasks() # Abort the request if the client disconnects. background_tasks.add_task(abort_request) return StreamingResponse(stream_results(), background=background_tasks) # Non-streaming case final_output = None async for request_output in results_generator: if await request.is_disconnected(): # Abort the request if the client disconnects. await engine.abort(request_id) return Response(status_code=499) final_output = request_output assert final_output is not None prompt = final_output.prompt text_outputs = [prompt + output.text for output in final_output.outputs] ret = {"text": text_outputs} return JSONResponse(ret)
Generate completion for the request. The request should be a JSON object with the following fields: - prompt: the prompt to use for the generation. - stream: whether to stream the results or not. - other fields: the sampling parameters (See `SamplingParams` for details).
155,760
import json from pathlib import Path from typing import Optional from typing import Union from transformers import AutoTokenizer, T5Tokenizer import tensorrt_llm def get_engine_version(engine_dir: str) -> Union[None, str]: engine_dir = Path(engine_dir) config_path = engine_dir / "config.json" with open(config_path, 'r') as f: config = json.load(f) if 'version' not in config: return None return config['version'] def read_model_name(engine_dir: str): engine_version = get_engine_version(engine_dir) with open(Path(engine_dir) / "config.json", 'r') as f: config = json.load(f) if engine_version is None: return config['builder_config']['name'] return config['pretrained_config']['architecture']
null
155,761
import json from pathlib import Path from typing import Optional from typing import Union from transformers import AutoTokenizer, T5Tokenizer import tensorrt_llm def throttle_generator(generator, stream_interval): for i, out in enumerate(generator): if not i % stream_interval: yield out if i % stream_interval: yield out
null
155,762
import json from pathlib import Path from typing import Optional from typing import Union from transformers import AutoTokenizer, T5Tokenizer import tensorrt_llm def load_tokenizer(tokenizer_dir: Optional[str] = None, vocab_file: Optional[str] = None, model_name: str = 'gpt', tokenizer_type: Optional[str] = None): if vocab_file is None: use_fast = True if tokenizer_type is not None and tokenizer_type == "llama": use_fast = False # Should set both padding_side and truncation_side to be 'left' tokenizer = AutoTokenizer.from_pretrained(tokenizer_dir, legacy=False, padding_side='left', truncation_side='left', trust_remote_code=True, tokenizer_type=tokenizer_type, use_fast=use_fast) else: # For gpt-next, directly load from tokenizer.model assert model_name == 'gpt' tokenizer = T5Tokenizer(vocab_file=vocab_file, padding_side='left', truncation_side='left') if model_name == 'qwen': with open(Path(tokenizer_dir) / "generation_config.json") as f: gen_config = json.load(f) chat_format = gen_config['chat_format'] if chat_format == 'raw': pad_id = gen_config['pad_token_id'] end_id = gen_config['eos_token_id'] elif chat_format == 'chatml': pad_id = tokenizer.im_end_id end_id = tokenizer.im_end_id else: raise Exception(f"unknown chat format: {chat_format}") elif model_name == 'glm_10b': pad_id = tokenizer.pad_token_id end_id = tokenizer.eop_token_id else: if tokenizer.pad_token_id is None: tokenizer.pad_token_id = tokenizer.eos_token_id pad_id = tokenizer.pad_token_id end_id = tokenizer.eos_token_id return tokenizer, pad_id, end_id
null
155,763
import argparse import gc import math import os import time from fastapi import FastAPI, Request from transformers import AutoTokenizer, AutoModel import uvicorn, json, datetime import torch import torch.distributed as dist from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer def get_prompt_llama2chinese( chat_history, system_prompt: str ) -> str: prompt = '' for input_text_one in chat_history: prompt += "<s>"+input_text_one['role']+": "+input_text_one['content'].strip()+"\n</s>" if chat_history[-1]['role']=='Human': prompt += "<s>Assistant: " else: prompt += "<s>Human: " prompt = prompt[-2048:] if len(system_prompt)>0: prompt = '<s>System: '+system_prompt.strip()+'\n</s>'+prompt return prompt
null
155,764
import argparse import gc import math import os import time from fastapi import FastAPI, Request from transformers import AutoTokenizer, AutoModel import uvicorn, json, datetime import torch import torch.distributed as dist from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer def get_prompt(chat_history, system_prompt: str): B_INST, E_INST = "[INST]", "[/INST]" B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n" sep = " " sep2 =" </s><s>" stop_token_ids = [2] system_template = f"[INST] <<SYS>>\n{system_prompt}\n<</SYS>>\n\n" roles = ("[INST]", "[/INST]") seps = [sep, sep2] if system_prompt.strip() != "": ret = system_template else: ret = "[INST] " for i, chat in enumerate(chat_history): message = chat["content"] role = chat["role"] if message: if i == 0: ret += message + " " else: if role == "Human": ret += "[INST]" + " " + message + seps[i % 2] else: ret += "[/INST]" + " " + message + seps[i % 2] else: if role == "Human": ret += "[INST]" else: ret += "[/INST]" print("prompt:{}".format(ret)) return ret async def create_item(request: Request): global model, tokenizer json_post_raw = await request.json() json_post = json.dumps(json_post_raw) json_post_list = json.loads(json_post) history = json_post_list.get('history') system_prompt = json_post_list.get('system_prompt') max_new_tokens = json_post_list.get('max_new_tokens') top_p = json_post_list.get('top_p') temperature = json_post_list.get('temperature') prompt = get_prompt(history, system_prompt) inputs = tokenizer([prompt], return_tensors='pt').to("cuda") generate_kwargs = dict( inputs, # streamer=streamer, max_new_tokens=max_new_tokens, do_sample=True, top_p=top_p, top_k=50, temperature=temperature, num_beams=1, repetition_penalty=1.2, max_length=2048, ) generate_ids = model.generate(**generate_kwargs) generate_ids = [item[len(inputs[0]):-1] for item in generate_ids] bot_message = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] if 'Human:' in bot_message: bot_message = bot_message.split('Human:')[0] now = datetime.datetime.now() time = now.strftime("%Y-%m-%d %H:%M:%S") answer = { "response": bot_message, "status": 200, "time": time } return answer
null
155,765
import argparse import gc import math import os import time from fastapi import FastAPI, Request from transformers import AutoTokenizer, AutoModel import uvicorn, json, datetime import torch import torch.distributed as dist from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer def get_world_size() -> int: if dist.is_initialized(): return dist.get_world_size() else: return 1
null
155,766
import argparse import gc import math import os import time from fastapi import FastAPI, Request from transformers import AutoTokenizer, AutoModel import uvicorn, json, datetime import torch import torch.distributed as dist from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer rank = local_rank def print_rank0(*msg): if rank != 0: return print(*msg)
null
155,767
import json import time import urllib.request import sys def test_api_server(input_text): header = {'Content-Type': 'application/json'} data = { "system_prompt": "", "history": inputs, "n" : 1, "best_of": 1, "presence_penalty": 1.2, "frequency_penalty": 0.2, "temperature": 0.3, "top_p" : 0.95, "top_k": 50, "use_beam_search": False, "stop": [], "ignore_eos" :False, "logprobs": None, "max_new_tokens": 2048, } request = urllib.request.Request( url='http://127.0.0.1:8001/generate', headers=header, data=json.dumps(data).encode('utf-8') ) result = None try: response = urllib.request.urlopen(request, timeout=300) res = response.read().decode('utf-8') result = json.loads(res) print(json.dumps(data, ensure_ascii=False, indent=2)) print(json.dumps(result, ensure_ascii=False, indent=2)) except Exception as e: print(e) return result
null
155,770
import glob import os import shutil import subprocess from os import path from setuptools import find_packages, setup from typing import List import torch from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension version = "0.3.0" cwd = os.path.dirname(os.path.abspath(__file__)) sha = "Unknown" try: sha = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=cwd).decode("ascii").strip() except Exception: pass def write_version_file(): version_path = os.path.join(cwd, "detrex", "version.py") with open(version_path, "w") as f: f.write(f"__version__ = '{version}'\n") f.write(f"git_version = {repr(sha)}\n")
null
155,771
import glob import os import shutil import subprocess from os import path from setuptools import find_packages, setup from typing import List import torch from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension The provided code snippet includes necessary dependencies for implementing the `get_detrex_configs` function. Write a Python function `def get_detrex_configs() -> List[str]` to solve the following problem: Return a list of configs to include in package for model zoo. Here is the function: def get_detrex_configs() -> List[str]: """ Return a list of configs to include in package for model zoo. """ source_configs_dir = path.join(path.dirname(path.realpath(__file__)), "configs") destination = path.join(path.dirname(path.realpath(__file__)), "detrex", "config", "configs") # Symlink the config directory inside package to have a cleaner pip install. # Remove stale symlink/directory from a previous build. if path.exists(source_configs_dir): if path.islink(destination): os.unlink(destination) elif path.isdir(destination): shutil.rmtree(destination) if not path.exists(destination): try: os.symlink(source_configs_dir, destination) except OSError: # Fall back to copying if symlink fails: ex. on Windows. shutil.copytree(source_configs_dir, destination) config_paths = glob.glob("configs/**/*.py", recursive=True) return config_paths
Return a list of configs to include in package for model zoo.
155,772
import glob import os import shutil import subprocess from os import path from setuptools import find_packages, setup from typing import List import torch from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension def get_extensions(): this_dir = os.path.dirname(os.path.abspath(__file__)) extensions_dir = os.path.join(this_dir, "detrex", "layers", "csrc") main_source = os.path.join(extensions_dir, "vision.cpp") sources = glob.glob(os.path.join(extensions_dir, "**", "*.cpp")) source_cuda = glob.glob(os.path.join(extensions_dir, "**", "*.cu")) + glob.glob( os.path.join(extensions_dir, "*.cu") ) sources = [main_source] + sources extension = CppExtension extra_compile_args = {"cxx": []} define_macros = [] if torch.cuda.is_available() and CUDA_HOME is not None: extension = CUDAExtension sources += source_cuda define_macros += [("WITH_CUDA", None)] extra_compile_args["nvcc"] = [ "-DCUDA_HAS_FP16=1", "-D__CUDA_NO_HALF_OPERATORS__", "-D__CUDA_NO_HALF_CONVERSIONS__", "-D__CUDA_NO_HALF2_OPERATORS__", ] else: define_macros += [("WITH_HIP", None)] extra_compile_args["nvcc"] = [] return None sources = [os.path.join(extensions_dir, s) for s in sources] include_dirs = [extensions_dir] ext_modules = [ extension( "detrex._C", sources, include_dirs=include_dirs, define_macros=define_macros, extra_compile_args=extra_compile_args, ) ] return ext_modules
null
155,773
import glob import os import shutil import subprocess from os import path from setuptools import find_packages, setup from typing import List import torch from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension version = "0.3.0" The provided code snippet includes necessary dependencies for implementing the `parse_requirements` function. Write a Python function `def parse_requirements(fname="requirements.txt", with_version=True)` to solve the following problem: Parse the package dependencies listed in a requirements file but strips specific versioning information. Args: fname (str): path to requirements file with_version (bool, default=False): if True include version specs Returns: List[str]: list of requirements items CommandLine: python -c "import setup; print(setup.parse_requirements())" Here is the function: def parse_requirements(fname="requirements.txt", with_version=True): """Parse the package dependencies listed in a requirements file but strips specific versioning information. Args: fname (str): path to requirements file with_version (bool, default=False): if True include version specs Returns: List[str]: list of requirements items CommandLine: python -c "import setup; print(setup.parse_requirements())" """ import re import sys from os.path import exists require_fpath = fname def parse_line(line): """Parse information from a line in a requirements text file.""" if line.startswith("-r "): # Allow specifying requirements in other files target = line.split(" ")[1] for info in parse_require_file(target): yield info else: info = {"line": line} if line.startswith("-e "): info["package"] = line.split("#egg=")[1] elif "@git+" in line: info["package"] = line else: # Remove versioning from the package pat = "(" + "|".join([">=", "==", ">"]) + ")" parts = re.split(pat, line, maxsplit=1) parts = [p.strip() for p in parts] info["package"] = parts[0] if len(parts) > 1: op, rest = parts[1:] if ";" in rest: # Handle platform specific dependencies # http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies version, platform_deps = map(str.strip, rest.split(";")) info["platform_deps"] = platform_deps else: version = rest # NOQA info["version"] = (op, version) yield info def parse_require_file(fpath): with open(fpath, "r") as f: for line in f.readlines(): line = line.strip() if line and not line.startswith("#"): for info in parse_line(line): yield info def gen_packages_items(): if exists(require_fpath): for info in parse_require_file(require_fpath): parts = [info["package"]] if with_version and "version" in info: parts.extend(info["version"]) if not sys.version.startswith("3.4"): # apparently package_deps are broken in 3.4 platform_deps = info.get("platform_deps") if platform_deps is not None: parts.append(";" + platform_deps) item = "".join(parts) yield item packages = list(gen_packages_items()) return packages
Parse the package dependencies listed in a requirements file but strips specific versioning information. Args: fname (str): path to requirements file with_version (bool, default=False): if True include version specs Returns: List[str]: list of requirements items CommandLine: python -c "import setup; print(setup.parse_requirements())"
155,774
import os import sys import detrex def setup(app): app.add_css_file("css/line_space.css")
null