index
int64
0
50.7k
project_path
stringclasses
279 values
completion_path
stringlengths
57
199
signature_postion
stringlengths
3
11
class_position
stringlengths
3
11
function_name
stringlengths
1
62
class_name
stringlengths
0
55
body_position
stringlengths
3
11
body_position_with_comments
stringlengths
3
11
masked_class
stringlengths
14
8.32k
masked_class_with_comment
stringlengths
14
8.32k
func_body
stringlengths
9
6.72k
func_body_with_comment
stringlengths
9
6.72k
len_func_body
int64
1
643
len_input
int64
10
2.02k
len_output
int64
4
1.9k
total
int64
20
2.05k
file_code
stringlengths
14
442k
file_code_with_comment
stringlengths
14
442k
1,017
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/serve/python_server.py
140,142
136,145
get_sample_data
Number
142,145
142,145
class Number(BaseModel): # deprecated - TODO remove this in favour of Category prediction: Optional[int] = None @staticmethod def get_sample_data() -> Dict[Any, Any]: FILL_FUNC_BODY
class Number(BaseModel): # deprecated - TODO remove this in favour of Category prediction: Optional[int] = None @staticmethod def get_sample_data() -> Dict[Any, Any]: FILL_FUNC_BODY
return {"prediction": 463}
return {"prediction": 463}
3
64
17
81
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,018
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/serve/python_server.py
238,240
145,329
_get_sample_dict_from_datatype
PythonServer
240,258
240,258
class PythonServer(LightningWork, abc.ABC): _start_method = "spawn" @requires(["torch"]) def __init__( # type: ignore self, input_type: type = _DefaultInputData, output_type: type = _DefaultOutputData, **kwargs: Any, ): """The PythonServer Class enables to easil...
class PythonServer(LightningWork, abc.ABC): _start_method = "spawn" @requires(["torch"]) def __init__( # type: ignore self, input_type: type = _DefaultInputData, output_type: type = _DefaultOutputData, **kwargs: Any, ): """The PythonServer Class enables to easil...
if hasattr(datatype, "get_sample_data"): return datatype.get_sample_data() datatype_props = datatype.schema()["properties"] out: Dict[str, Any] = {} for k, v in datatype_props.items(): if v["type"] == "string": out[k] = "data string" e...
if hasattr(datatype, "get_sample_data"): return datatype.get_sample_data() datatype_props = datatype.schema()["properties"] out: Dict[str, Any] = {} for k, v in datatype_props.items(): if v["type"] == "string": out[k] = "data string" e...
53
1,693
195
1,888
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,019
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/serve/python_server.py
119,121
112,136
request_code_sample
Text
121,136
121,136
class Text(BaseModel): text: Optional[str] = None @staticmethod def get_sample_data() -> Dict[Any, Any]: return {"text": "A portrait of a person looking away from the camera"} @staticmethod def request_code_sample(url: str) -> str: FILL_FUNC_BODY
class Text(BaseModel): text: Optional[str] = None @staticmethod def get_sample_data() -> Dict[Any, Any]: return {"text": "A portrait of a person looking away from the camera"} @staticmethod def request_code_sample(url: str) -> str: FILL_FUNC_BODY
return f""" import base64 from pathlib import Path import requests response = requests.post('{url}', json={{ "text": "A portrait of a person looking away from the camera" }}) # If you are using basic authentication for your app, you should add your credentials to the request: # response = requests.post('{u...
return f""" import base64 from pathlib import Path import requests response = requests.post('{url}', json={{ "text": "A portrait of a person looking away from the camera" }}) # If you are using basic authentication for your app, you should add your credentials to the request: # response = requests.post('{u...
66
92
150
242
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,020
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/serve/serve.py
154,155
1,171
_maybe_create_instance
157,168
155,168
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
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(mo...
"""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_na...
36
1,557
209
1,766
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,021
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/serve/serve.py
102,103
53,154
run
ModelInferenceAPI
103,135
103,135
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 ...
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 ...
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_FI...
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_FI...
74
729
376
1,105
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,022
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/serve/serve.py
49,50
38,53
run
_InferenceCallable
50,53
50,53
class _InferenceCallable: def __init__( self, deserialize: Callable, predict: Callable, serialize: Callable, ): self.deserialize = deserialize self.predict = predict self.serialize = serialize async def run(self, data) -> Any: FILL_FUNC_BODY
class _InferenceCallable: def __init__( self, deserialize: Callable, predict: Callable, serialize: Callable, ): self.deserialize = deserialize self.predict = predict self.serialize = serialize async def run(self, data) -> Any: FILL_FUNC_BODY
return self.serialize(self.predict(self.deserialize(data)))
return self.serialize(self.predict(self.deserialize(data)))
2
98
25
123
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,023
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/training.py
186,187
128,204
run
LightningTrainerScript
187,197
187,197
class LightningTrainerScript(LightningFlow): def __init__( self, script_path: str, script_args: Optional[Union[list, str]] = None, num_nodes: int = 1, cloud_compute: CloudCompute = CloudCompute("default"), sanity_serving: bool = False, script_runner: Type[Trac...
class LightningTrainerScript(LightningFlow): def __init__( self, script_path: str, script_args: Optional[Union[list, str]] = None, num_nodes: int = 1, cloud_compute: CloudCompute = CloudCompute("default"), sanity_serving: bool = False, script_runner: Type[Trac...
for work in self.ws: if all(w.internal_ip for w in self.ws): internal_urls = [(w.internal_ip, w.port) for w in self.ws] work.run(internal_urls=internal_urls, **run_kwargs) if all(w.has_finished for w in self.ws): for w in self.ws: ...
for work in self.ws: if all(w.internal_ip for w in self.ws): internal_urls = [(w.internal_ip, w.port) for w in self.ws] work.run(internal_urls=internal_urls, **run_kwargs) if all(w.has_finished for w in self.ws): for w in self.ws: ...
33
657
126
783
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,024
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/training.py
66,67
28,128
run
PyTorchLightningScriptRunner
67,87
67,87
class PyTorchLightningScriptRunner(TracerPythonScript): def __init__( self, script_path: str, script_args: Optional[Union[list, str]] = None, node_rank: int = 1, num_nodes: int = 1, sanity_serving: bool = False, cloud_compute: Optional[CloudCompute] = None, ...
class PyTorchLightningScriptRunner(TracerPythonScript): def __init__( self, script_path: str, script_args: Optional[Union[list, str]] = None, node_rank: int = 1, num_nodes: int = 1, sanity_serving: bool = False, cloud_compute: Optional[CloudCompute] = None, ...
if not internal_urls: # Note: This is called only once. _logger.info(f"The node {self.node_rank} started !") return None if self.env: os.environ.update(self.env) distributed_env_vars = { "MASTER_ADDR": internal_urls[0][0], ...
if not internal_urls: # Note: This is called only once. _logger.info(f"The node {self.node_rank} started !") return None if self.env: os.environ.update(self.env) distributed_env_vars = { "MASTER_ADDR": internal_urls[0][0], ...
39
819
239
1,058
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,026
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/core/api.py
428,429
425,442
run
LightningUvicornServer
429,436
429,436
class LightningUvicornServer(uvicorn.Server): has_started_queue: Optional[Queue] = None def run(self, sockets: Optional[List[socket.socket]] = None) -> None: FILL_FUNC_BODY async def check_is_started(self, queue: Queue) -> None: while not self.started: await asyncio.sleep(0.1) qu...
class LightningUvicornServer(uvicorn.Server): has_started_queue: Optional[Queue] = None def run(self, sockets: Optional[List[socket.socket]] = None) -> None: FILL_FUNC_BODY async def check_is_started(self, queue: Queue) -> None: while not self.started: await asyncio.sleep(0.1) qu...
self.config.setup_event_loop() loop = asyncio.get_event_loop() asyncio.ensure_future(self.serve(sockets=sockets)) if self.has_started_queue: asyncio.ensure_future(self.check_is_started(self.has_started_queue)) loop.run_forever()
self.config.setup_event_loop() loop = asyncio.get_event_loop() asyncio.ensure_future(self.serve(sockets=sockets)) if self.has_started_queue: asyncio.ensure_future(self.check_is_started(self.has_started_queue)) loop.run_forever()
9
126
100
226
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,027
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/core/api.py
118,119
93,138
run_once
UIRefresher
119,133
119,133
class UIRefresher(Thread): def __init__( self, api_publish_state_queue: Queue, api_response_queue: Queue, refresh_interval: float = 0.1, ) -> None: super().__init__(daemon=True) self.api_publish_state_queue = api_publish_state_queue self.api_response_queue...
class UIRefresher(Thread): def __init__( self, api_publish_state_queue: Queue, api_response_queue: Queue, refresh_interval: float = 0.1, ) -> None: super().__init__(daemon=True) self.api_publish_state_queue = api_publish_state_queue self.api_response_queue...
with contextlib.suppress(queue.Empty): global app_status state, app_status = self.api_publish_state_queue.get(timeout=0) with lock: global_app_state_store.set_app_state(TEST_SESSION_UUID, state) with contextlib.suppress(queue.Empty): respo...
with contextlib.suppress(queue.Empty): global app_status state, app_status = self.api_publish_state_queue.get(timeout=0) with lock: global_app_state_store.set_app_state(TEST_SESSION_UUID, state) with contextlib.suppress(queue.Empty): respo...
38
304
168
472
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,030
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/core/flow.py
858,859
840,862
configure_layout
_RootFlow
859,862
859,862
class _RootFlow(LightningFlow): def __init__(self, work: LightningWork) -> None: super().__init__() self.work = work @property def ready(self) -> bool: ready = getattr(self.work, "ready", None) if ready is not None: return ready return self.work.url != ""...
class _RootFlow(LightningFlow): def __init__(self, work: LightningWork) -> None: super().__init__() self.work = work @property def ready(self) -> bool: ready = getattr(self.work, "ready", None) if ready is not None: return ready return self.work.url != ""...
if is_overridden("configure_layout", self.work): return [{"name": "Main", "content": self.work}] return []
if is_overridden("configure_layout", self.work): return [{"name": "Main", "content": self.work}] return []
10
170
41
211
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,032
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/frontend/just_py/just_py.py
98,99
27,115
start_server
JustPyFrontend
99,112
99,112
class JustPyFrontend(Frontend): """A frontend for wrapping JustPy code in your LightingFlow. Return this in your `LightningFlow.configure_layout()` method if you wish to build the UI with ``justpy``. To use this frontend, you must first install the `justpy` package (if running locally): .. code-block:...
class JustPyFrontend(Frontend): """A frontend for wrapping JustPy code in your LightingFlow. Return this in your `LightningFlow.configure_layout()` method if you wish to build the UI with ``justpy``. To use this frontend, you must first install the `justpy` package (if running locally): .. code-block:...
env = os.environ.copy() env["LIGHTNING_FLOW_NAME"] = self.flow.name # type: ignore env["LIGHTNING_RENDER_FUNCTION"] = self.render_fn.__name__ env["LIGHTNING_RENDER_MODULE_FILE"] = inspect.getmodule(self.render_fn).__file__ # type: ignore env["LIGHTNING_HOST"] = host env...
env = os.environ.copy() env["LIGHTNING_FLOW_NAME"] = self.flow.name # type: ignore env["LIGHTNING_RENDER_FUNCTION"] = self.render_fn.__name__ env["LIGHTNING_RENDER_MODULE_FILE"] = inspect.getmodule(self.render_fn).__file__ # type: ignore env["LIGHTNING_HOST"] = host env...
45
649
269
918
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,033
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/frontend/panel/app_state_comm.py
36,37
1,102
_get_ws_port
37,42
37,42
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
if "LIGHTNING_APP_STATE_URL" in os.environ: return 8080 return APP_SERVER_PORT
if "LIGHTNING_APP_STATE_URL" in os.environ: return 8080 return APP_SERVER_PORT
8
913
45
958
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,034
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/frontend/panel/panel_frontend.py
190,191
1,194
_get_allowed_hosts
192,194
191,194
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# TODO: Enable only lightning.ai domain in the cloud return "*"
"""Returns a comma separated list of host[:port] that should be allowed to connect.""" # TODO: Enable only lightning.ai domain in the cloud return "*"
11
1,856
21
1,877
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,035
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/frontend/panel/panel_frontend.py
159,160
44,190
_get_popen_args
PanelFrontend
160,190
160,190
class PanelFrontend(Frontend): """The `PanelFrontend` enables you to serve Panel code as a Frontend for your LightningFlow. Reference: https://lightning.ai/lightning-docs/workflows/add_web_ui/panel/ Args: entry_point: The path to a .py or .ipynb file, or a pure function. The file or function must ...
class PanelFrontend(Frontend): """The `PanelFrontend` enables you to serve Panel code as a Frontend for your LightningFlow. Reference: https://lightning.ai/lightning-docs/workflows/add_web_ui/panel/ Args: entry_point: The path to a .py or .ipynb file, or a pure function. The file or function must ...
if callable(self.entry_point): path = str(pathlib.Path(__file__).parent / "panel_serve_render_fn.py") else: path = pathlib.Path(self.entry_point) abs_path = str(path) # The app is served at http://localhost:{port}/{flow}/{entry_point} # Lightning embeds h...
if callable(self.entry_point): path = str(pathlib.Path(__file__).parent / "panel_serve_render_fn.py") else: path = pathlib.Path(self.entry_point) abs_path = str(path) # The app is served at http://localhost:{port}/{flow}/{entry_point} # Lightning embeds h...
63
1,152
293
1,445
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,036
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/frontend/stream_lit.py
110,111
28,114
stop_server
StreamlitFrontend
111,114
111,114
class StreamlitFrontend(Frontend): """A frontend for wrapping Streamlit code in your LightingFlow. Return this in your `LightningFlow.configure_layout()` method if you wish to build the UI with ``streamlit``. To use this frontend, you must first install the `streamlit` package (if running locally): .....
class StreamlitFrontend(Frontend): """A frontend for wrapping Streamlit code in your LightingFlow. Return this in your `LightningFlow.configure_layout()` method if you wish to build the UI with ``streamlit``. To use this frontend, you must first install the `streamlit` package (if running locally): .....
if self._process is None: raise RuntimeError("Server is not running. Call `StreamlitFrontend.start_server()` first.") self._process.kill()
if self._process is None: raise RuntimeError("Server is not running. Call `StreamlitFrontend.start_server()` first.") self._process.kill()
13
841
46
887
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,037
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/frontend/streamlit_base.py
36,37
1,51
_main
38,49
37,49
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
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. ...
"""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 functi...
39
416
138
554
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,038
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/frontend/utils.py
48,49
1,73
_get_frontend_environment
61,73
49,73
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
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_...
"""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' Ret...
27
608
190
798
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,039
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/frontend/web.py
105,106
1,141
_get_log_config
107,133
106,133
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# 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", ...
"""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": ...
65
1,285
285
1,570
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,040
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/frontend/web.py
55,56
30,76
start_server
StaticWebFrontend
56,70
56,70
class StaticWebFrontend(Frontend): """A frontend that serves static files from a directory using FastAPI. Return this in your `LightningFlow.configure_layout()` method if you wish to serve a HTML page. Arguments: serve_dir: A local directory to serve files from. This directory should at least cont...
class StaticWebFrontend(Frontend): """A frontend that serves static files from a directory using FastAPI. Return this in your `LightningFlow.configure_layout()` method if you wish to serve a HTML page. Arguments: serve_dir: A local directory to serve files from. This directory should at least cont...
log_file = str(get_logfile()) self._process = mp.Process( target=_start_server, kwargs={ "host": host, "port": port, "serve_dir": self.serve_dir, "path": f"/{self.flow.name}", "log_file": log_file, ...
log_file = str(get_logfile()) self._process = mp.Process( target=_start_server, kwargs={ "host": host, "port": port, "serve_dir": self.serve_dir, "path": f"/{self.flow.name}", "log_file": log_file, ...
23
331
132
463
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,043
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/launcher/lightning_hybrid_backend.py
97,98
19,156
delete_work
CloudHybridBackend
98,103
98,103
class CloudHybridBackend(Backend): def __init__(self, *args, **kwargs): super().__init__(*args, queues=QueuingSystem(CLOUD_QUEUE_TYPE), **kwargs) cloud_backend = CloudBackend(*args, **kwargs) kwargs.pop("queue_id") multiprocess_backend = MultiProcessingBackend(*args, **kwargs) ...
class CloudHybridBackend(Backend): def __init__(self, *args, **kwargs): super().__init__(*args, queues=QueuingSystem(CLOUD_QUEUE_TYPE), **kwargs) cloud_backend = CloudBackend(*args, **kwargs) kwargs.pop("queue_id") multiprocess_backend = MultiProcessingBackend(*args, **kwargs) ...
backend = self._get_backend(work) if isinstance(backend, MultiProcessingBackend): self._prepare_work_stop(app, work) backend.delete_work(app, work)
backend = self._get_backend(work) if isinstance(backend, MultiProcessingBackend): self._prepare_work_stop(app, work) backend.delete_work(app, work)
10
1,567
60
1,627
import os from typing import Optional from lightning_cloud.openapi import AppinstancesIdBody, Externalv1LightningappInstance from lightning.app.core import constants from lightning.app.core.queues import QueuingSystem from lightning.app.launcher.lightning_backend import CloudBackend from lightning.app.runners.backend...
import os from typing import Optional from lightning_cloud.openapi import AppinstancesIdBody, Externalv1LightningappInstance from lightning.app.core import constants from lightning.app.core.queues import QueuingSystem from lightning.app.launcher.lightning_backend import CloudBackend from lightning.app.runners.backend...
1,044
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/pdb/pdb.py
48,49
1,51
set_trace
49,51
49,51
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
pdb = MPPdb() pdb.set_trace(sys._getframe().f_back)
pdb = MPPdb() pdb.set_trace(sys._getframe().f_back)
4
453
29
482
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,045
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/pdb/pdb.py
35,36
29,48
_cmdloop
MPPdb
36,48
36,48
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: FILL_FUNC_BODY
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: FILL_FUNC_BODY
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: ...
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: ...
25
84
114
198
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,047
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/plugin/plugin.py
55,56
40,117
run_job
LightningPlugin
67,102
56,102
class LightningPlugin: """A ``LightningPlugin`` is a single-file Python class that can be executed within a cloudspace to perform actions.""" def __init__(self) -> None: self.project_id = "" self.cloudspace_id = "" self.cluster_id = "" self.source_app = "" self.keep_...
class LightningPlugin: """A ``LightningPlugin`` is a single-file Python class that can be executed within a cloudspace to perform actions.""" def __init__(self) -> None: self.project_id = "" self.cloudspace_id = "" self.cluster_id = "" self.source_app = "" self.keep_...
from lightning.app.runners.backends.cloud import CloudBackend from lightning.app.runners.cloud import CloudRuntime logger.info(f"Processing job run request. name: {name}, app_entrypoint: {app_entrypoint}, env_vars: {env_vars}") # Dispatch the job _set_flow_context() en...
"""Run a job in the cloudspace associated with this plugin. Args: name: The name of the job. app_entrypoint: The path of the file containing the app to run. env_vars: Additional env vars to set when running the app. Returns: The spec of the creat...
65
430
416
846
# Copyright The Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
# Copyright The Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
1,048
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/runners/backends/backend.py
54,62
26,123
_dynamic_run_wrapper
Backend
62,91
62,91
class Backend(ABC): """The Backend provides and interface for the framework to communicate with resources in the cloud.""" def __init__(self, entrypoint_file: str, queues: QueuingSystem, queue_id: str) -> None: self.queues: QueuingSystem = queues self.queue_id = queue_id self.entrypoint...
class Backend(ABC): """The Backend provides and interface for the framework to communicate with resources in the cloud.""" def __init__(self, entrypoint_file: str, queues: QueuingSystem, queue_id: str) -> None: self.queues: QueuingSystem = queues self.queue_id = queue_id self.entrypoint...
if not work.name: # the name is empty, which means this work was never assigned to a parent flow raise AttributeError( f"Failed to create process for {work.__class__.__name__}." f" Make sure to set this work as an attribute of a `LightningFlow` before call...
if not work.name: # the name is empty, which means this work was never assigned to a parent flow raise AttributeError( f"Failed to create process for {work.__class__.__name__}." f" Make sure to set this work as an attribute of a `LightningFlow` before call...
102
1,005
289
1,294
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,049
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/runners/backends/cloud.py
42,43
25,50
stop_all_works
CloudBackend
43,45
43,45
class CloudBackend(Backend): def __init__( self, entrypoint_file, queue_id: Optional[str] = None, status_update_interval: Optional[int] = None, client_max_tries: Optional[int] = None, ): super().__init__(entrypoint_file, queues=QueuingSystem.MULTIPROCESS, queue_id...
class CloudBackend(Backend): def __init__( self, entrypoint_file, queue_id: Optional[str] = None, status_update_interval: Optional[int] = None, client_max_tries: Optional[int] = None, ): super().__init__(entrypoint_file, queues=QueuingSystem.MULTIPROCESS, queue_id...
raise NotImplementedError
raise NotImplementedError
2
334
11
345
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,050
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/runners/backends/mp_process.py
131,132
116,138
stop_work
CloudMultiProcessingBackend
132,136
132,136
class CloudMultiProcessingBackend(MultiProcessingBackend): def __init__(self, *args: Any, **kwargs: Any): super().__init__(*args, **kwargs) # Note: Track the open ports to close them on termination. self.ports = [] def create_work(self, app, work) -> None: work._host = "0.0.0.0...
class CloudMultiProcessingBackend(MultiProcessingBackend): def __init__(self, *args: Any, **kwargs: Any): super().__init__(*args, **kwargs) # Note: Track the open ports to close them on termination. self.ports = [] def create_work(self, app, work) -> None: work._host = "0.0.0.0...
disable_port(work._port) self.ports = [port for port in self.ports if port != work._port] return super().stop_work(app, work)
disable_port(work._port) self.ports = [port for port in self.ports if port != work._port] return super().stop_work(app, work)
15
250
50
300
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,051
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/runners/backends/mp_process.py
58,59
28,75
restart
MultiProcessWorkManager
59,71
59,71
class MultiProcessWorkManager(WorkManager): def __init__(self, app, work): self.app = app self.work = work self._process = None def start(self): self._work_runner = WorkRunner( work=self.work, work_name=self.work.name, caller_queue=self.app.ca...
class MultiProcessWorkManager(WorkManager): def __init__(self, app, work): self.app = app self.work = work self._process = None def start(self): self._work_runner = WorkRunner( work=self.work, work_name=self.work.name, caller_queue=self.app.ca...
assert not self.is_alive() work = self._work_runner.work # un-wrap ProxyRun. is_proxy = isinstance(work.run, ProxyWorkRun) if is_proxy: work_run = work.run work.run = work_run.work_run work._restarting = True self.start() if is_prox...
assert not self.is_alive() work = self._work_runner.work # un-wrap ProxyRun. is_proxy = isinstance(work.run, ProxyWorkRun) if is_proxy: work_run = work.run work.run = work_run.work_run work._restarting = True self.start() if is_prox...
30
417
123
540
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,052
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/runners/backends/mp_process.py
112,113
75,116
delete_work
MultiProcessingBackend
113,116
113,116
class MultiProcessingBackend(Backend): def __init__(self, entrypoint_file: str): super().__init__(entrypoint_file=entrypoint_file, queues=QueuingSystem.MULTIPROCESS, queue_id="0") def create_work(self, app, work) -> None: if constants.LIGHTNING_CLOUDSPACE_HOST is not None: # Overrid...
class MultiProcessingBackend(Backend): def __init__(self, entrypoint_file: str): super().__init__(entrypoint_file=entrypoint_file, queues=QueuingSystem.MULTIPROCESS, queue_id="0") def create_work(self, app, work) -> None: if constants.LIGHTNING_CLOUDSPACE_HOST is not None: # Overrid...
self.stop_work(app, work)
self.stop_work(app, work)
2
543
17
560
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,053
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/runners/multiprocess.py
48,49
36,161
dispatch
MultiProcessRuntime
50,150
49,150
@dataclass class MultiProcessRuntime(Runtime): """Runtime to launch the LightningApp into multiple processes. The MultiProcessRuntime will generate 1 process for each :class:`~lightning.app.core.work.LightningWork` and attach queues to enable communication between the different processes. """ bac...
@dataclass class MultiProcessRuntime(Runtime): """Runtime to launch the LightningApp into multiple processes. The MultiProcessRuntime will generate 1 process for each :class:`~lightning.app.core.work.LightningWork` and attach queues to enable communication between the different processes. """ bac...
try: _set_flow_context() # Note: In case the runtime is used in the cloud. in_cloudspace = constants.LIGHTNING_CLOUDSPACE_HOST is not None self.host = "0.0.0.0" if constants.APP_SERVER_IN_CLOUD or in_cloudspace else self.host # noqa: S104 self.app.b...
"""Method to dispatch and run the LightningApp.""" try: _set_flow_context() # Note: In case the runtime is used in the cloud. in_cloudspace = constants.LIGHTNING_CLOUDSPACE_HOST is not None self.host = "0.0.0.0" if constants.APP_SERVER_IN_CLOUD or in_clou...
228
299
1,226
1,525
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,055
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/runners/runtime.py
128,129
104,183
terminate
Runtime
130,169
129,169
@dataclass class Runtime: app: Optional[LightningApp] = None entrypoint: Optional[Path] = None start_server: bool = True host: str = APP_SERVER_HOST port: int = APP_SERVER_PORT processes: Dict[str, multiprocessing.Process] = field(default_factory=dict) threads: List[Thread] = field(default_f...
@dataclass class Runtime: app: Optional[LightningApp] = None entrypoint: Optional[Path] = None start_server: bool = True host: str = APP_SERVER_HOST port: int = APP_SERVER_PORT processes: Dict[str, multiprocessing.Process] = field(default_factory=dict) threads: List[Thread] = field(default_f...
logger.info("Your Lightning App is being stopped. This won't take long.") self.done = False has_messaged = False while not self.done: try: if self.app.backend is not None: self.app.backend.stop_all_works(self.app.works) if ...
"""This method is used to terminate all the objects (threads, processes, etc..) created by the app.""" logger.info("Your Lightning App is being stopped. This won't take long.") self.done = False has_messaged = False while not self.done: try: if self.ap...
108
563
426
989
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,056
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/runners/runtime_type.py
28,29
24,34
get_runtime
RuntimeType
29,34
29,34
class RuntimeType(Enum): MULTIPROCESS = "multiprocess" CLOUD = "cloud" def get_runtime(self) -> Type["Runtime"]: FILL_FUNC_BODY
class RuntimeType(Enum): MULTIPROCESS = "multiprocess" CLOUD = "cloud" def get_runtime(self) -> Type["Runtime"]: FILL_FUNC_BODY
if self == RuntimeType.MULTIPROCESS: return MultiProcessRuntime if self == RuntimeType.CLOUD: return CloudRuntime raise ValueError("Unknown runtime type")
if self == RuntimeType.MULTIPROCESS: return MultiProcessRuntime if self == RuntimeType.CLOUD: return CloudRuntime raise ValueError("Unknown runtime type")
16
57
52
109
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,057
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/source_code/hashing.py
19,20
1,52
_get_hash
38,52
20,52
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# validate input if algorithm == "blake2": h = hashlib.blake2b(digest_size=20) elif algorithm == "md5": h = hashlib.md5() else: raise ValueError(f"Algorithm {algorithm} not supported") # calculate hash for all files for file in files: with open(file, "rb") as f: ...
"""Hashes the contents of a list of files. Parameters ---------- files: List[Path] List of files. algorithm: str, default "blake2" Algorithm to hash contents. "blake2" is set by default because it is faster than "md5". [1] chunk_num_blocks: int, default 128 Block...
49
415
164
579
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,058
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/source_code/local.py
118,119
28,150
package
LocalSourceCodeDir
120,127
119,127
class LocalSourceCodeDir: """Represents the source code directory and provide the utilities to manage it.""" def __init__( self, path: Path, ignore_functions: Optional[List[_IGNORE_FUNCTION]] = None, default_ignore: bool = True, package_source: bool = True, sys_c...
class LocalSourceCodeDir: """Represents the source code directory and provide the utilities to manage it.""" def __init__( self, path: Path, ignore_functions: Optional[List[_IGNORE_FUNCTION]] = None, default_ignore: bool = True, package_source: bool = True, sys_c...
if self.package_path.exists(): return self.package_path # create a packaging session if not available with self.packaging_session() as session_path: _tar_path(source_path=session_path, target_file=str(self.package_path), compression=True) return self.package_path ...
"""Packages local path using tar.""" if self.package_path.exists(): return self.package_path # create a packaging session if not available with self.packaging_session() as session_path: _tar_path(source_path=session_path, target_file=str(self.package_path), compre...
21
1,312
91
1,403
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,059
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/source_code/tar.py
168,169
1,202
_tar_path_subprocess
181,202
169,202
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Only add compression when users explicitly request it. # We do this because it takes too long to compress # large datastores. tar_flags = "-cvf" if compression: tar_flags = "-zcvf" if os.path.isdir(source_path): command = f"tar -C {source_path} {tar_flags} {target_file} ./" ...
"""Create tar from directory using `tar` Parameters ---------- source_path: str Source directory or file target_file Target tar file compression: bool, default False Enable compression, which is disabled by default. """ # Only add compression when users explicit...
69
1,628
275
1,903
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,060
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/source_code/uploader.py
58,59
23,112
upload_data
FileUploader
78,91
59,91
class FileUploader: """This class uploads a source file with presigned url to S3. Attributes ---------- source_file: str Source file to upload presigned_url: str Presigned urls dictionary, with key as part number and values as urls retries: int Amount of retries when req...
class FileUploader: """This class uploads a source file with presigned url to S3. Attributes ---------- source_file: str Source file to upload presigned_url: str Presigned urls dictionary, with key as part number and values as urls retries: int Amount of retries when req...
disconnect_retries = retries while disconnect_retries > 0: try: retries = Retry(total=10) with requests.Session() as s: s.mount("https://", HTTPAdapter(max_retries=retries)) return self._upload_data(s, url, data) ...
"""Send data to url. Parameters ---------- url: str url string to send data to data: bytes Bytes of data to send to url retries: int Amount of retries disconnect_retry_wait_seconds: int Amount of seconds between di...
35
764
145
909
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,061
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/storage/copier.py
109,114
1,156
_copy_files
122,156
114,156
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
if fs is None: fs = _filesystem() def _copy(from_path: pathlib.Path, to_path: pathlib.Path) -> Optional[Exception]: _logger.debug(f"Copying {str(from_path)} -> {str(to_path)}") try: # NOTE: S3 does not have a concept of directories, so we do not need to create one. ...
"""Copy files from one path to another. The source path must either be an existing file or folder. If the source is a folder, the destination path is interpreted as a folder as well. If the source is a file, the destination path is interpreted as a file too. Files in a folder are copied recursively an...
143
1,298
468
1,766
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,062
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/storage/copier.py
73,74
39,101
join
_Copier
74,77
74,77
class _Copier(Thread): """The Copier is a thread running alongside a LightningWork. It maintains two queues that connect to the central :class:`~lightning.app.storage.orchestrator.StorageOrchestrator`, the request queue and the response queue. The Copier waits for a request to be pushed to the request ...
class _Copier(Thread): """The Copier is a thread running alongside a LightningWork. It maintains two queues that connect to the central :class:`~lightning.app.storage.orchestrator.StorageOrchestrator`, the request queue and the response queue. The Copier waits for a request to be pushed to the request ...
self._exit_event.set() super().join(timeout)
self._exit_event.set() super().join(timeout)
2
735
22
757
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,065
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/storage/filesystem.py
12,13
1,167
_get_files
13,31
13,31
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...
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...
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 ...
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 ...
43
1,625
203
1,828
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...
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...
1,066
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/storage/filesystem.py
105,106
31,167
walk
FileSystem
112,140
106,140
class FileSystem: """This filesystem enables to easily move files from and to the shared storage.""" def __init__(self) -> None: self._fs = _filesystem() self._root = str(_shared_storage_path()) def put(self, src_path: str, dst_path: str, put_fn: Callable = _copy_files) -> None: ""...
class FileSystem: """This filesystem enables to easily move files from and to the shared storage.""" def __init__(self) -> None: self._fs = _filesystem() self._root = str(_shared_storage_path()) def put(self, src_path: str, dst_path: str, put_fn: Callable = _copy_files) -> None: ""...
if not path.startswith("/"): raise Exception(f"The provided destination {path} needs to start with `/`.") shared_path = Path(os.path.join(self._root, path[1:])).resolve() if not self._fs.exists(shared_path): raise RuntimeError(f"The provided path {shared_path} doesn't e...
"""This method enables to list files from the shared storage in a blocking fashion. Arguments: path: The path to files to list. """ if not path.startswith("/"): raise Exception(f"The provided destination {path} needs to start with `/`.") shared_path = P...
80
1,260
293
1,553
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...
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...
1,067
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/storage/mount.py
69,71
24,76
protocol
Mount
72,76
71,76
@dataclass class Mount: """Allows you to mount the contents of an AWS S3 bucket on disk when running an app on the cloud. Arguments: source: The location which contains the external data which should be mounted in the running work. At the moment, only AWS S3 mounts are supported. This must ...
@dataclass class Mount: """Allows you to mount the contents of an AWS S3 bucket on disk when running an app on the cloud. Arguments: source: The location which contains the external data which should be mounted in the running work. At the moment, only AWS S3 mounts are supported. This must ...
for protocol in __MOUNT_PROTOCOLS__: if self.source.startswith(protocol): return protocol return ""
"""The backing storage protocol indicated by this drive source.""" for protocol in __MOUNT_PROTOCOLS__: if self.source.startswith(protocol): return protocol return ""
10
545
40
585
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,068
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/storage/payload.py
268,269
264,275
save
Payload
269,272
269,272
class Payload(_BasePayload): """The Payload object enables to transfer python objects from one work to another in a similar fashion as :class:`~lightning.app.storage.path.Path`.""" def save(self, obj: Any, path: str) -> None: FILL_FUNC_BODY def load(self, path: str) -> Any: with open(path, "rb")...
class Payload(_BasePayload): """The Payload object enables to transfer python objects from one work to another in a similar fashion as :class:`~lightning.app.storage.path.Path`.""" def save(self, obj: Any, path: str) -> None: FILL_FUNC_BODY def load(self, path: str) -> Any: with open(path, "rb")...
with open(path, "wb") as f: pickle.dump(obj, f)
with open(path, "wb") as f: pickle.dump(obj, f)
7
118
29
147
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,070
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/structures/dict.py
25,26
1,161
_prepare_name
26,30
26,30
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
return str(component.name.split(".")[-1]) # TODO: add support and tests for dict operations (insertion, update, etc.)
return str(component.name.split(".")[-1]) # TODO: add support and tests for dict operations (insertion, update, etc.)
14
1,727
40
1,767
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,071
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/structures/dict.py
121,123
30,161
state
Dict
124,131
123,131
class Dict(t.Dict[str, T]): def __init__(self, **kwargs: T): """The Dict Object is used to represents dict collection of :class:`~lightning.app.core.work.LightningWork` or :class:`~lightning.app.core.flow.LightningFlow`. Example: >>> from lightning.app import LightningFlow, Lig...
class Dict(t.Dict[str, T]): def __init__(self, **kwargs: T): """The Dict Object is used to represents dict collection of :class:`~lightning.app.core.work.LightningWork` or :class:`~lightning.app.core.flow.LightningFlow`. Example: >>> from lightning.app import LightningFlow, Lig...
from lightning.app.core import LightningFlow, LightningWork return { "works": {key: item.state for key, item in self.items() if isinstance(item, LightningWork)}, "flows": {key: item.state for key, item in self.items() if isinstance(item, LightningFlow)}, }
"""Returns the state of its flows and works.""" from lightning.app.core import LightningFlow, LightningWork return { "works": {key: item.state for key, item in self.items() if isinstance(item, LightningWork)}, "flows": {key: item.state for key, item in self.items() if is...
30
1,404
93
1,497
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,072
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/structures/list.py
25,26
1,178
_prepare_name
26,30
26,30
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
return str(component.name.split(".")[-1]) # TODO: add support and tests for list operations (concatenation, deletion, insertion, etc.)
return str(component.name.split(".")[-1]) # TODO: add support and tests for list operations (concatenation, deletion, insertion, etc.)
15
1,834
45
1,879
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,073
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/structures/list.py
116,118
30,178
state
List
119,128
118,128
class List(t.List[T]): def __init__(self, *items: T): """The List Object is used to represents list collection of :class:`~lightning.app.core.work.LightningWork` or :class:`~lightning.app.core.flow.LightningFlow`. Example: >>> from lightning.app import LightningFlow, LightningW...
class List(t.List[T]): def __init__(self, *items: T): """The List Object is used to represents list collection of :class:`~lightning.app.core.work.LightningWork` or :class:`~lightning.app.core.flow.LightningFlow`. Example: >>> from lightning.app import LightningFlow, LightningW...
from lightning.app.core import LightningFlow, LightningWork works = [item for item in self if isinstance(item, LightningWork)] children = [item for item in self if isinstance(item, LightningFlow)] return { "works": {_prepare_name(w): w.state for w in works}, "flo...
"""Returns the state of its flows and works.""" from lightning.app.core import LightningFlow, LightningWork works = [item for item in self if isinstance(item, LightningWork)] children = [item for item in self if isinstance(item, LightningFlow)] return { "works": {_pr...
42
1,489
117
1,606
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,074
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/app_commands.py
43,44
1,128
_extract_commands_from_file
49,83
44,83
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
cl = CommandLines( file=file_name, ) with open(file_name) as f: file_lines = f.readlines() for line_number, line in enumerate(file_lines): line = line.strip() if line in APP_COMMAND_LINES_TO_IGNORE: continue # stop parsing at first non-comment line a...
"""Extract all lines at the top of the file which contain commands to execute. The return struct contains a list of commands to execute with the corresponding line number the command executed on. """ cl = CommandLines( file=file_name, ) with open(file_name) as f: file_lines = f...
122
972
329
1,301
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,075
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/app_logs.py
74,82
1,138
_app_logs_reader
82,138
82,138
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
read_queue = queue.PriorityQueue() # We will use a socket per component log_sockets = [ logs_api_client.create_lightning_logs_socket( project_id=project_id, app_id=app_id, component=component_name, on_message_callback=_push_log_events_to_read_queue_ca...
read_queue = queue.PriorityQueue() # We will use a socket per component log_sockets = [ logs_api_client.create_lightning_logs_socket( project_id=project_id, app_id=app_id, component=component_name, on_message_callback=_push_log_events_to_read_queue_ca...
223
742
636
1,378
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,076
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/auth.py
41,42
1,62
_credential_string_to_basic_auth_params
47,62
42,62
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
if credential_string.count(":") != 1: raise ValueError( "Credential string must follow the format username:password; " + f"the provided one ('{credential_string}') does not." ) username, password = credential_string.split(":") if not username: raise ValueErr...
"""Returns the name/ID pair for each given Secret name. Raises a `ValueError` if any of the given Secret names do not exist. """ if credential_string.count(":") != 1: raise ValueError( "Credential string must follow the format username:password; " + f"the provided one (...
47
449
141
590
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,077
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/auth.py
31,32
24,41
_get_api_token
_AuthTokenGetter
32,41
32,41
class _AuthTokenGetter: def __init__(self, api_client: ApiClient): self.api_client = api_client self._auth = Auth() self._auth.authenticate() self._auth_service = AuthServiceApi(api_client) def _get_api_token(self) -> str: FILL_FUNC_BODY
class _AuthTokenGetter: def __init__(self, api_client: ApiClient): self.api_client = api_client self._auth = Auth() self._auth.authenticate() self._auth_service = AuthServiceApi(api_client) def _get_api_token(self) -> str: FILL_FUNC_BODY
token_resp = self._auth_service.auth_service_login( body=V1LoginRequest( username=self._auth.username, api_key=self._auth.api_key, ) ) return token_resp.token
token_resp = self._auth_service.auth_service_login( body=V1LoginRequest( username=self._auth.username, api_key=self._auth.api_key, ) ) return token_resp.token
10
96
76
172
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,079
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/cli_helpers.py
200,201
121,238
_collect_open_api_json
_LightningAppOpenAPIRetriever
202,238
201,238
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...
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...
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.jso...
"""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: ...
146
1,008
501
1,509
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,080
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/cloud.py
26,27
1,64
_get_project
28,57
27,57
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
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 ...
"""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( "Environmen...
80
415
345
760
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,081
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/clusters.py
24,25
1,53
_get_default_cluster
30,53
25,53
import random from lightning_cloud.openapi import ProjectIdProjectclustersbindingsBody, V1ClusterType from lightning_cloud.openapi.rest import ApiException from lightning.app.utilities.network import LightningClient def _ensure_cluster_project_binding(client: LightningClient, project_id: str, cluster_id: str) -> No...
import random from lightning_cloud.openapi import ProjectIdProjectclustersbindingsBody, V1ClusterType from lightning_cloud.openapi.rest import ApiException from lightning.app.utilities.network import LightningClient def _ensure_cluster_project_binding(client: LightningClient, project_id: str, cluster_id: str) -> No...
cluster_bindings = client.projects_service_list_project_cluster_bindings(project_id=project_id).clusters if not cluster_bindings: raise ValueError(f"No clusters are bound to the project {project_id}.") if len(cluster_bindings) == 1: return cluster_bindings[0].cluster_id clusters = [] ...
"""This utility implements a minimal version of the cluster selection logic used in the cloud. TODO: This should be requested directly from the platform. """ cluster_bindings = client.projects_service_list_project_cluster_bindings(project_id=project_id).clusters if not cluster_bindings: r...
73
303
281
584
import random from lightning_cloud.openapi import ProjectIdProjectclustersbindingsBody, V1ClusterType from lightning_cloud.openapi.rest import ApiException from lightning.app.utilities.network import LightningClient def _ensure_cluster_project_binding(client: LightningClient, project_id: str, cluster_id: str) -> No...
import random from lightning_cloud.openapi import ProjectIdProjectclustersbindingsBody, V1ClusterType from lightning_cloud.openapi.rest import ApiException from lightning.app.utilities.network import LightningClient def _ensure_cluster_project_binding(client: LightningClient, project_id: str, cluster_id: str) -> No...
1,082
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/component.py
52,53
1,153
_sanitize_state
58,82
53,82
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
from lightning.app.storage import Drive, Path from lightning.app.storage.payload import _BasePayload def sanitize_path(path: Path) -> Path: path_copy = Path(path) path_copy._sanitize() return path_copy def sanitize_payload(payload: _BasePayload): return type(payload).fr...
"""Utility function to sanitize the state of a component. Sanitization enables the state to be deep-copied and hashed. """ from lightning.app.storage import Drive, Path from lightning.app.storage.payload import _BasePayload def sanitize_path(path: Path) -> Path: path_copy = Path(path)...
61
1,342
321
1,663
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,083
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/dependency_caching.py
19,20
1,28
get_hash
21,28
20,28
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
h = hashlib.blake2b(digest_size=20) if not path.exists(): raise FileNotFoundError(f"{path} does not exist") with path.open("rb") as f: for chunk in iter(lambda: f.read(chunk_num_blocks * h.block_size), b""): h.update(chunk) return h.hexdigest()
"""Get the hash of a file.""" h = hashlib.blake2b(digest_size=20) if not path.exists(): raise FileNotFoundError(f"{path} does not exist") with path.open("rb") as f: for chunk in iter(lambda: f.read(chunk_num_blocks * h.block_size), b""): h.update(chunk) return h.hexdigest...
26
211
110
321
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,084
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/enum.py
63,64
1,83
make_status
64,75
64,75
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
status = { "stage": stage, "timestamp": datetime.now(tz=timezone.utc).timestamp(), } if message: status["message"] = message if reason: status["reason"] = reason return status
status = { "stage": stage, "timestamp": datetime.now(tz=timezone.utc).timestamp(), } if message: status["message"] = message if reason: status["reason"] = reason return status
20
695
77
772
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,085
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/exceptions.py
35,36
22,52
invoke
_ApiExceptionHandler
36,52
36,52
class _ApiExceptionHandler(Group): """Attempts to convert ApiExceptions to ClickExceptions. This process clarifies the error for the user by: 1. Showing the error message from the lightning.ai servers, instead of showing the entire HTTP response 2. Suppressing long tracebacks However, if th...
class _ApiExceptionHandler(Group): """Attempts to convert ApiExceptions to ClickExceptions. This process clarifies the error for the user by: 1. Showing the error message from the lightning.ai servers, instead of showing the entire HTTP response 2. Suppressing long tracebacks However, if th...
try: return super().invoke(ctx) except ApiException as api: exception_messages = [] if 400 <= api.status < 500: try: body = loads(api.body) except JSONDecodeError: raise api except...
try: return super().invoke(ctx) except ApiException as api: exception_messages = [] if 400 <= api.status < 500: try: body = loads(api.body) except JSONDecodeError: raise api except...
31
143
137
280
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,086
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/frontend.py
32,33
1,90
update_index_file
33,65
33,65
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
import shutil from pathlib import Path entry_file = Path(ui_root) / "index.html" original_file = Path(ui_root) / "index.original.html" if not original_file.exists(): shutil.copyfile(entry_file, original_file) # keep backup else: # revert index.html in case it was modified afte...
import shutil from pathlib import Path entry_file = Path(ui_root) / "index.html" original_file = Path(ui_root) / "index.original.html" if not original_file.exists(): shutil.copyfile(entry_file, original_file) # keep backup else: # revert index.html in case it was modified afte...
118
640
424
1,064
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,087
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/git.py
60,61
1,87
check_if_remote_head_is_different
67,79
61,79
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Check SHA values. local_sha = execute_git_command(["rev-parse", "@"]) remote_sha = execute_git_command(["rev-parse", r"@{u}"]) base_sha = execute_git_command(["merge-base", "@", r"@{u}"]) # Whenever a SHA is not avaialble, just return. if any("fatal" in f for f in (local_sha, remote_sha, base...
"""Checks if remote git repository is different than the version available locally. This only compares the local SHA to the HEAD commit of a given branch. This check won't be used if user isn't in a HEAD locally. """ # Check SHA values. local_sha = execute_git_command(["rev-parse", "@"]) r...
44
815
160
975
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,088
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/imports.py
51,52
1,149
requires
52,74
52,74
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
if not isinstance(module_paths, list): module_paths = [module_paths] def decorator(func): @functools.wraps(func) def wrapper(*args: Any, **kwargs: Any): unavailable_modules = [f"'{module}'" for module in module_paths if not module_available(module)] if any(unavai...
if not isinstance(module_paths, list): module_paths = [module_paths] def decorator(func): @functools.wraps(func) def wrapper(*args: Any, **kwargs: Any): unavailable_modules = [f"'{module}'" for module in module_paths if not module_available(module)] if any(unavai...
61
1,016
234
1,250
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,090
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/introspection.py
43,44
24,56
visit_ClassDef
LightningVisitor
44,56
44,56
class LightningVisitor(ast.NodeVisitor): """Base class for visitor that finds class definitions based on class inheritance. Derived classes are expected to define class_name and implement the analyze_class_def method. Attributes ---------- class_name: str Name of class to identify, to be de...
class LightningVisitor(ast.NodeVisitor): """Base class for visitor that finds class definitions based on class inheritance. Derived classes are expected to define class_name and implement the analyze_class_def method. Attributes ---------- class_name: str Name of class to identify, to be de...
bases = [] for base in node.bases: if type(base) == ast.Attribute: bases.append(base.attr) elif type(base) == ast.Name: bases.append(base.id) if self.class_name in bases: entry = {"name": node.name, "type": self.class_name} ...
bases = [] for base in node.bases: if type(base) == ast.Attribute: bases.append(base.attr) elif type(base) == ast.Name: bases.append(base.id) if self.class_name in bases: entry = {"name": node.name, "type": self.class_name} ...
29
190
131
321
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,091
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/introspection.py
319,320
277,376
has_class
Scanner
320,343
320,343
class Scanner: """Finds relevant Lightning objects in files in the file system. Attributes ---------- visitor_classes: List[Type] List of visitor classes to use when traversing files. Parameters ---------- path: str Path to file, or directory where to look for files to scan....
class Scanner: """Finds relevant Lightning objects in files in the file system. Attributes ---------- visitor_classes: List[Type] List of visitor classes to use when traversing files. Parameters ---------- path: str Path to file, or directory where to look for files to scan....
# This method isn't strong enough as it is using only `ImportFrom`. # TODO: Use proper classDef scanning. classes = [] for path in self.paths: try: module = ast.parse(path.open().read()) except SyntaxError: print(f"Error while pars...
# This method isn't strong enough as it is using only `ImportFrom`. # TODO: Use proper classDef scanning. classes = [] for path in self.paths: try: module = ast.parse(path.open().read()) except SyntaxError: print(f"Error while pars...
64
670
228
898
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,094
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/log.py
20,21
1,24
get_logfile
21,24
21,24
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
log_dir = Path(_storage_root_dir(), "frontend") log_dir.mkdir(parents=True, exist_ok=True) return log_dir / filename
log_dir = Path(_storage_root_dir(), "frontend") log_dir.mkdir(parents=True, exist_ok=True) return log_dir / filename
10
209
48
257
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,095
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/log_helpers.py
41,42
1,50
_error_callback
42,50
42,50
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
errors = { KeyError: "Malformed log message, missing key", JSONDecodeError: "Malformed log message", TypeError: "Malformed log format", ValueError: "Malformed date format", } logger.error(f"⚡ Error while reading logs ({errors.get(type(error), 'Unknown')}), {error}") ws_ap...
errors = { KeyError: "Malformed log message, missing key", JSONDecodeError: "Malformed log message", TypeError: "Malformed log format", ValueError: "Malformed date format", } logger.error(f"⚡ Error while reading logs ({errors.get(type(error), 'Unknown')}), {error}") ws_ap...
31
376
108
484
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,096
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/login.py
57,58
49,151
load
Auth
65,74
58,74
@dataclass class Auth: username: Optional[str] = None user_id: Optional[str] = None api_key: Optional[str] = None secrets_file = pathlib.Path(LIGHTNING_CREDENTIAL_PATH) def load(self) -> bool: FILL_FUNC_BODY def save(self, token: str = "", user_id: str = "", api_key: str = "", username: str = "...
@dataclass class Auth: username: Optional[str] = None user_id: Optional[str] = None api_key: Optional[str] = None secrets_file = pathlib.Path(LIGHTNING_CREDENTIAL_PATH) def load(self) -> bool: """Load credentials from disk and update properties with credentials. Returns --...
if not self.secrets_file.exists(): logger.debug("Credentials file not found.") return False with self.secrets_file.open() as creds: credentials = json.load(creds) for key in Keys: setattr(self, key.suffix, credentials.get(key.suffix, None))...
"""Load credentials from disk and update properties with credentials. Returns ---------- True if credentials are available. """ if not self.secrets_file.exists(): logger.debug("Credentials file not found.") return False with self.secrets_...
26
910
103
1,013
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,097
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/login.py
158,159
151,214
login_with_browser
AuthServer
159,214
159,214
class AuthServer: @staticmethod def get_auth_url(port: int) -> str: redirect_uri = f"http://localhost:{port}/login-complete" params = urlencode({"redirectTo": redirect_uri}) return f"{get_lightning_cloud_url()}/sign-in?{params}" def login_with_browser(self, auth: Auth) -> None: FILL...
class AuthServer: @staticmethod def get_auth_url(port: int) -> str: redirect_uri = f"http://localhost:{port}/login-complete" params = urlencode({"redirectTo": redirect_uri}) return f"{get_lightning_cloud_url()}/sign-in?{params}" def login_with_browser(self, auth: Auth) -> None: FILL...
app = FastAPI() port = find_free_network_port() url = self.get_auth_url(port) try: # check if server is reachable or catch any network errors requests.head(url) except requests.ConnectionError as ex: raise requests.ConnectionError( ...
app = FastAPI() port = find_free_network_port() url = self.get_auth_url(port) try: # check if server is reachable or catch any network errors requests.head(url) except requests.ConnectionError as ex: raise requests.ConnectionError( ...
221
115
746
861
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,098
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/login.py
44,46
39,49
suffix
Keys
46,49
46,49
class Keys(Enum): USERNAME = "LIGHTNING_USERNAME" USER_ID = "LIGHTNING_USER_ID" API_KEY = "LIGHTNING_API_KEY" @property def suffix(self): FILL_FUNC_BODY
class Keys(Enum): USERNAME = "LIGHTNING_USERNAME" USER_ID = "LIGHTNING_USER_ID" API_KEY = "LIGHTNING_API_KEY" @property def suffix(self): FILL_FUNC_BODY
return self.value.lstrip("LIGHTNING_").lower()
return self.value.lstrip("LIGHTNING_").lower()
2
77
23
100
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,099
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/logs_socket_api.py
24,26
23,95
_app_logs_socket_url
_LightningLogsSocketAPI
26,31
26,31
class _LightningLogsSocketAPI(_AuthTokenGetter): @staticmethod def _app_logs_socket_url(host: str, project_id: str, app_id: str, token: str, component: str) -> str: FILL_FUNC_BODY def create_lightning_logs_socket( self, project_id: str, app_id: str, component: str, on_...
class _LightningLogsSocketAPI(_AuthTokenGetter): @staticmethod def _app_logs_socket_url(host: str, project_id: str, app_id: str, token: str, component: str) -> str: FILL_FUNC_BODY def create_lightning_logs_socket( self, project_id: str, app_id: str, component: str, on_...
return ( f"wss://{host}/v1/projects/{project_id}/appinstances/{app_id}/logs?" f"token={token}&component={component}&follow=true" )
return ( f"wss://{host}/v1/projects/{project_id}/appinstances/{app_id}/logs?" f"token={token}&component={component}&follow=true" )
5
707
62
769
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,101
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/openapi.py
19,20
1,76
_duplicate_checker
21,31
20,31
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
result = {} for name, value in js: if name in result: raise ValueError( f"Unable to load JSON. A duplicate key {name} was detected. JSON objects must have unique keys." ) result[name] = value return result
"""_duplicate_checker verifies that your JSON object doesn't contain duplicate keys.""" result = {} for name, value in js: if name in result: raise ValueError( f"Unable to load JSON. A duplicate key {name} was detected. JSON objects must have unique keys." ) ...
36
686
80
766
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,102
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/packaging/app_config.py
65,66
1,77
_get_config_file
72,77
66,77
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
source_path = pathlib.Path(source_path).absolute() if source_path.is_file(): source_path = source_path.parent return pathlib.Path(source_path / _APP_CONFIG_FILENAME)
"""Get the Lightning app config file '.lightning' at the given source path. Args: source_path: A path to a folder or a file. """ source_path = pathlib.Path(source_path).absolute() if source_path.is_file(): source_path = source_path.parent return pathlib.Path(source_path / _APP...
12
705
66
771
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,103
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/packaging/app_config.py
47,49
26,65
load_from_file
AppConfig
50,54
49,54
@dataclass class AppConfig: """The AppConfig holds configuration metadata for the application. Args: name: Optional name of the application. If not provided, auto-generates a new name. """ name: str = field(default_factory=get_unique_name) def save_to_file(self, path: Union[str, pathlib....
@dataclass class AppConfig: """The AppConfig holds configuration metadata for the application. Args: name: Optional name of the application. If not provided, auto-generates a new name. """ name: str = field(default_factory=get_unique_name) def save_to_file(self, path: Union[str, pathlib....
with open(path) as file: config = yaml.safe_load(file) return cls(**config)
"""Load the configuration from the given file.""" with open(path) as file: config = yaml.safe_load(file) return cls(**config)
9
381
37
418
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,105
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/packaging/build_config.py
147,148
67,202
_find_requirements
BuildConfig
148,160
148,160
@dataclass class BuildConfig: """The Build Configuration describes how the environment a LightningWork runs in should be set up. Arguments: requirements: List of requirements or list of paths to requirement files. If not passed, they will be automatically extracted from a `requirements.txt`...
@dataclass class BuildConfig: """The Build Configuration describes how the environment a LightningWork runs in should be set up. Arguments: requirements: List of requirements or list of paths to requirement files. If not passed, they will be automatically extracted from a `requirements.txt`...
# 1. Get work file file = _get_work_file(work) if file is None: return [] # 2. Try to find a requirement file associated the file. dirname = os.path.dirname(file) try: requirements = load_requirements(dirname, filename) except NotADirectory...
# 1. Get work file file = _get_work_file(work) if file is None: return [] # 2. Try to find a requirement file associated the file. dirname = os.path.dirname(file) try: requirements = load_requirements(dirname, filename) except NotADirectory...
47
1,362
124
1,486
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,107
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/packaging/cloud_compute.py
142,144
63,178
from_dict
CloudCompute
144,162
144,162
@dataclass class CloudCompute: """Configure the cloud runtime for a lightning work or flow. Arguments: name: The name of the hardware to use. A full list of supported options can be found in :doc:`/core_api/lightning_work/compute`. If you have a request for more hardware options, please con...
@dataclass class CloudCompute: """Configure the cloud runtime for a lightning work or flow. Arguments: name: The name of the hardware to use. A full list of supported options can be found in :doc:`/core_api/lightning_work/compute`. If you have a request for more hardware options, please con...
assert d.pop("type") == __CLOUD_COMPUTE_IDENTIFIER__ mounts = d.pop("mounts", None) if mounts is None: pass elif isinstance(mounts, dict): d["mounts"] = Mount(**mounts) elif isinstance(mounts, (list)): d["mounts"] = [] for mount in ...
assert d.pop("type") == __CLOUD_COMPUTE_IDENTIFIER__ mounts = d.pop("mounts", None) if mounts is None: pass elif isinstance(mounts, dict): d["mounts"] = Mount(**mounts) elif isinstance(mounts, (list)): d["mounts"] = [] for mount in ...
52
1,185
221
1,406
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,108
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/packaging/cloud_compute.py
50,51
25,60
remove
_CloudComputeStore
51,60
51,60
@dataclass class _CloudComputeStore: id: str component_names: List[str] def add_component_name(self, new_component_name: str) -> None: found_index = None # When the work is being named by the flow, pop its previous names for index, component_name in enumerate(self.component_names): ...
@dataclass class _CloudComputeStore: id: str component_names: List[str] def add_component_name(self, new_component_name: str) -> None: found_index = None # When the work is being named by the flow, pop its previous names for index, component_name in enumerate(self.component_names): ...
found_index = None for index, component_name in enumerate(self.component_names): if new_component_name == component_name: found_index = index if found_index is not None: del self.component_names[found_index]
found_index = None for index, component_name in enumerate(self.component_names): if new_component_name == component_name: found_index = index if found_index is not None: del self.component_names[found_index]
22
300
80
380
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,109
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/packaging/tarfile.py
42,43
1,53
extract_tarfile
44,53
43,53
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
if not os.path.exists(file_path): return 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...
"""This utility extracts all files from a tarfile.""" if not os.path.exists(file_path): return 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) exc...
26
413
116
529
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,110
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/port.py
83,84
1,169
enable_port
85,126
84,126
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
app_id = os.getenv("LIGHTNING_CLOUD_APP_ID", None) project_id = os.getenv("LIGHTNING_CLOUD_PROJECT_ID", None) if not app_id or not project_id: raise Exception("The app_id and project_id should be defined.") client = LightningClient() list_apps_resp = client.lightningapp_instance_service_li...
"""Make a request to the cloud controlplane to open a port of the flow.""" app_id = os.getenv("LIGHTNING_CLOUD_APP_ID", None) project_id = os.getenv("LIGHTNING_CLOUD_PROJECT_ID", None) if not app_id or not project_id: raise Exception("The app_id and project_id should be defined.") client =...
101
1,437
450
1,887
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,112
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/proxies.py
189,190
112,225
sanitize
ProxyWorkRun
190,200
190,200
@dataclass class ProxyWorkRun: work_run: Callable work_name: str # TODO: remove this argument and get the name from work.name directly work: "LightningWork" caller_queue: "BaseQueue" def __post_init__(self): self.work_state = None def __call__(self, *args: Any, **kwargs: Any): ...
@dataclass class ProxyWorkRun: work_run: Callable work_name: str # TODO: remove this argument and get the name from work.name directly work: "LightningWork" caller_queue: "BaseQueue" def __post_init__(self): self.work_state = None def __call__(self, *args: Any, **kwargs: Any): ...
if isinstance(obj, Path): # create a copy of the Path and erase the consumer # the LightningWork on the receiving end of the caller queue will become the new consumer # this is necessary to make the Path deepdiff-hashable path_copy = Path(obj) ...
if isinstance(obj, Path): # create a copy of the Path and erase the consumer # the LightningWork on the receiving end of the caller queue will become the new consumer # this is necessary to make the Path deepdiff-hashable path_copy = Path(obj) ...
50
1,326
117
1,443
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,113
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/proxies.py
366,368
356,390
enable_spawn
WorkRunExecutor
368,373
368,373
@dataclass class WorkRunExecutor: work: "LightningWork" work_run: Callable delta_queue: "BaseQueue" enable_start_observer: bool = True def __call__(self, *args, **kwargs): return self.work_run(*args, **kwargs) @contextmanager def enable_spawn(self) -> Generator: FILL_FUNC_BODY d...
@dataclass class WorkRunExecutor: work: "LightningWork" work_run: Callable delta_queue: "BaseQueue" enable_start_observer: bool = True def __call__(self, *args, **kwargs): return self.work_run(*args, **kwargs) @contextmanager def enable_spawn(self) -> Generator: FILL_FUNC_BODY d...
self.work._setattr_replacement = None self.work._backend = None self._clean_queues() yield
self.work._setattr_replacement = None self.work._backend = None self._clean_queues() yield
8
282
41
323
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,115
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/proxies.py
280,281
225,313
run_once
WorkStateObserver
281,308
281,308
class WorkStateObserver(Thread): """This thread runs alongside LightningWork and periodically checks for state changes. If the state changed from one interval to the next, it will compute the delta and add it to the queue which is connected to the Flow. This enables state changes to be captured that are not...
class WorkStateObserver(Thread): """This thread runs alongside LightningWork and periodically checks for state changes. If the state changed from one interval to the next, it will compute the delta and add it to the queue which is connected to the Flow. This enables state changes to be captured that are not...
with _state_observer_lock: # Add all deltas the LightningWorkSetAttrProxy has processed and sent to the Flow already while # the WorkStateObserver was sleeping for delta in self._delta_memory: self._last_state += delta self._delta_memory.clear() ...
with _state_observer_lock: # Add all deltas the LightningWorkSetAttrProxy has processed and sent to the Flow already while # the WorkStateObserver was sleeping for delta in self._delta_memory: self._last_state += delta self._delta_memory.clear() ...
88
582
354
936
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,116
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/safe_pickle.py
29,31
1,108
_trimmed_work
32,41
31,41
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
holder = {} for arg in to_trim: holder[arg] = getattr(work, arg) setattr(work, arg, None) yield for arg in to_trim: setattr(work, arg, holder[arg])
"""Context manager to trim the work object to remove attributes that are not picklable.""" holder = {} for arg in to_trim: holder[arg] = getattr(work, arg) setattr(work, arg, None) yield for arg in to_trim: setattr(work, arg, holder[arg])
22
1,275
75
1,350
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,117
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/scheduler.py
39,40
25,61
run_once
SchedulerThread
40,58
40,58
class SchedulerThread(threading.Thread): # TODO (tchaton) Abstract this logic to a generic scheduling service. def __init__(self, app) -> None: super().__init__(daemon=True) self._exit_event = threading.Event() self._sleep_time = 1.0 self._app = app def run(self) -> None: ...
class SchedulerThread(threading.Thread): # TODO (tchaton) Abstract this logic to a generic scheduling service. def __init__(self, app) -> None: super().__init__(daemon=True) self._exit_event = threading.Event() self._sleep_time = 1.0 self._app = app def run(self) -> None: ...
for call_hash in list(self._app._schedules.keys()): metadata = self._app._schedules[call_hash] start_time = datetime.fromisoformat(metadata["start_time"]) current_date = datetime.now() next_event = croniter(metadata["cron_pattern"], start_time).get_next(datetime) ...
for call_hash in list(self._app._schedules.keys()): metadata = self._app._schedules[call_hash] start_time = datetime.fromisoformat(metadata["start_time"]) current_date = datetime.now() next_event = croniter(metadata["cron_pattern"], start_time).get_next(datetime) ...
50
195
236
431
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,118
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/secrets.py
21,22
1,42
_names_to_ids
27,42
22,42
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
lightning_client = LightningClient() project = _get_project(lightning_client) secrets = lightning_client.secret_service_list_secrets(project_id=project.project_id) secret_names_to_ids: Dict[str, str] = {} for secret in secrets.secrets: if secret.name in secret_names: secret_nam...
"""Returns the name/ID pair for each given Secret name. Raises a `ValueError` if any of the given Secret names do not exist. """ lightning_client = LightningClient() project = _get_project(lightning_client) secrets = lightning_client.secret_service_list_secrets(project_id=project.project_id) ...
43
271
187
458
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,119
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/tracer.py
29,30
1,194
wrap_fn
31,93
30,93
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
class_name = cls.__qualname__ @functools.wraps(fn) def fn_with_tracing(self, *args: Any, **kwargs: Any): if class_name not in trace: trace[class_name] = {} self_id = id(self) stack = inspect.stack() frame = stack[stack_level] frame_id = id(frame) ...
"""Wrap a function so that its execution can be traced and its args and return values modified.""" class_name = cls.__qualname__ @functools.wraps(fn) def fn_with_tracing(self, *args: Any, **kwargs: Any): if class_name not in trace: trace[class_name] = {} self_id = id(self) ...
216
1,276
693
1,969
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,120
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/tracer.py
164,165
93,194
trace
Tracer
170,194
165,194
class Tracer: def __init__(self): self.methods = [] self.orig = {} self.res = {} def add_traced(self, cls, method_name, stack_level=1, pre_fn=None, post_fn=None): """Record the fact that we will want to trace method_name in class cls. Optionally provide two functions th...
class Tracer: def __init__(self): self.methods = [] self.orig = {} self.res = {} def add_traced(self, cls, method_name, stack_level=1, pre_fn=None, post_fn=None): """Record the fact that we will want to trace method_name in class cls. Optionally provide two functions th...
args = list(args) script = args[0] script_dir = Path(script).parent.absolute() sys_path = sys.path[:] sys_argv = sys.argv[:] sys.path.append(str(script_dir)) sys.argv = args self._instrument() res = runpy.run_path(script, run_name="__main__", ...
"""Execute the command-line arguments in args after instrumenting for tracing. Restore the classes to their initial state after tracing. """ args = list(args) script = args[0] script_dir = Path(script).parent.absolute() sys_path = sys.path[:] sys_argv =...
40
788
207
995
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,121
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/utilities/tree.py
24,25
1,89
breadth_first
32,35
25,35
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
yield from _BreadthFirstVisitor(root, types)
"""Returns a generator that walks through the tree of components breadth-first. Arguments: root: The root component of the tree types: If provided, only the component types in this list will be visited. """ yield from _BreadthFirstVisitor(root, types)
4
794
21
815
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,122
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/_graveyard/tpu.py
109,110
1,124
_patch_classes
110,120
110,120
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
setattr(fabric.strategies, "SingleTPUStrategy", SingleTPUStrategy) setattr(fabric.accelerators, "TPUAccelerator", TPUAccelerator) setattr(fabric.plugins, "TPUPrecision", TPUPrecision) setattr(fabric.plugins.precision, "TPUPrecision", TPUPrecision) setattr(fabric.plugins, "TPUBf16Precision", TPUBf16P...
setattr(fabric.strategies, "SingleTPUStrategy", SingleTPUStrategy) setattr(fabric.accelerators, "TPUAccelerator", TPUAccelerator) setattr(fabric.plugins, "TPUPrecision", TPUPrecision) setattr(fabric.plugins.precision, "TPUPrecision", TPUPrecision) setattr(fabric.plugins, "TPUBf16Precision", TPUBf16P...
24
1,290
232
1,522
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,123
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/_graveyard/tpu.py
45,47
34,51
register_strategies
SingleTPUStrategy
47,51
47,51
class SingleTPUStrategy(SingleDeviceXLAStrategy): """Legacy class. Use :class:`~lightning.fabric.strategies.single_xla.SingleDeviceXLAStrategy` instead. """ def __init__(self, *args: Any, **kwargs: Any) -> None: rank_zero_deprecation("The 'single_tpu' strategy is deprecated. Use 'single_xla' ...
class SingleTPUStrategy(SingleDeviceXLAStrategy): """Legacy class. Use :class:`~lightning.fabric.strategies.single_xla.SingleDeviceXLAStrategy` instead. """ def __init__(self, *args: Any, **kwargs: Any) -> None: rank_zero_deprecation("The 'single_tpu' strategy is deprecated. Use 'single_xla' ...
if "single_tpu" not in strategy_registry: strategy_registry.register("single_tpu", cls, description="Legacy class. Use `single_xla` instead.")
if "single_tpu" not in strategy_registry: strategy_registry.register("single_tpu", cls, description="Legacy class. Use `single_xla` instead.")
12
168
55
223
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,124
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/accelerators/cpu.py
75,76
1,97
_parse_cpu_cores
90,97
76,97
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
if isinstance(cpu_cores, str) and cpu_cores.strip().isdigit(): cpu_cores = int(cpu_cores) if not isinstance(cpu_cores, int) or cpu_cores <= 0: raise TypeError("`devices` selected with `CPUAccelerator` should be an int > 0.") return cpu_cores
"""Parses the cpu_cores given in the format as accepted by the ``devices`` argument in the :class:`~lightning.pytorch.trainer.trainer.Trainer`. Args: cpu_cores: An int > 0. Returns: An int representing the number of processes Raises: MisconfigurationException: ...
29
784
105
889
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,125
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/accelerators/cpu.py
26,28
23,75
setup_device
CPUAccelerator
33,36
28,36
class CPUAccelerator(Accelerator): """Accelerator for CPU devices.""" @override def setup_device(self, device: torch.device) -> None: FILL_FUNC_BODY @override def teardown(self) -> None: pass @staticmethod @override def parse_devices(devices: Union[int, str, List[int]]) -> int: ...
class CPUAccelerator(Accelerator): """Accelerator for CPU devices.""" @override def setup_device(self, device: torch.device) -> None: """ Raises: ValueError: If the selected device is not CPU. """ FILL_FUNC_BODY @override def teardown(self) -> None...
if device.type != "cpu": raise ValueError(f"Device should be CPU, got {device} instead.")
""" Raises: ValueError: If the selected device is not CPU. """ if device.type != "cpu": raise ValueError(f"Device should be CPU, got {device} instead.")
12
394
34
428
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,127
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/accelerators/cuda.py
58,61
25,79
auto_device_count
CUDAAccelerator
62,64
61,64
class CUDAAccelerator(Accelerator): """Accelerator for NVIDIA CUDA devices.""" @override def setup_device(self, device: torch.device) -> None: """ Raises: ValueError: If the selected device is not of type CUDA. """ if device.type != "cuda": ...
class CUDAAccelerator(Accelerator): """Accelerator for NVIDIA CUDA devices.""" @override def setup_device(self, device: torch.device) -> None: """ Raises: ValueError: If the selected device is not of type CUDA. """ if device.type != "cuda": ...
return num_cuda_devices()
"""Get the devices when set to auto.""" return num_cuda_devices()
2
483
13
496
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,128
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/accelerators/mps.py
87,88
1,93
_get_all_available_mps_gpus
92,93
88,93
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
return [0] if MPSAccelerator.is_available() else []
""" Returns: A list of all available MPS GPUs """ return [0] if MPSAccelerator.is_available() else []
6
872
20
892
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,129
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/accelerators/mps.py
69,73
26,87
is_available
MPSAccelerator
74,77
73,77
class MPSAccelerator(Accelerator): """Accelerator for Metal Apple Silicon GPU devices. .. warning:: Use of this accelerator beyond import and instantiation is experimental. """ @override def setup_device(self, device: torch.device) -> None: """ Raises: ValueError: ...
class MPSAccelerator(Accelerator): """Accelerator for Metal Apple Silicon GPU devices. .. warning:: Use of this accelerator beyond import and instantiation is experimental. """ @override def setup_device(self, device: torch.device) -> None: """ Raises: ValueError: ...
mps_disabled = os.getenv("DISABLE_MPS", "0") == "1" return not mps_disabled and torch.backends.mps.is_available() and platform.processor() in ("arm", "arm64")
"""MPS is only available on a machine with the ARM-based Apple Silicon processors.""" mps_disabled = os.getenv("DISABLE_MPS", "0") == "1" return not mps_disabled and torch.backends.mps.is_available() and platform.processor() in ("arm", "arm64")
16
536
65
601
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,130
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/accelerators/registry.py
118,119
1,130
call_register_accelerators
124,130
119,130
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
import importlib module = importlib.import_module(base_module) from lightning.fabric.accelerators.accelerator import Accelerator _register_classes(registry, "register_accelerators", module, Accelerator)
"""Legacy. Do not use. """ import importlib module = importlib.import_module(base_module) from lightning.fabric.accelerators.accelerator import Accelerator _register_classes(registry, "register_accelerators", module, Accelerator)
13
1,165
73
1,238
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,131
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/accelerators/registry.py
87,89
22,118
get
_AcceleratorRegistry
95,106
89,106
class _AcceleratorRegistry(dict): """This class is a Registry that stores information about the Accelerators. The Accelerators are mapped to strings. These strings are names that identify an accelerator, e.g., "gpu". It also returns Optional description and parameters to initialize the Accelerator, whi...
class _AcceleratorRegistry(dict): """This class is a Registry that stores information about the Accelerators. The Accelerators are mapped to strings. These strings are names that identify an accelerator, e.g., "gpu". It also returns Optional description and parameters to initialize the Accelerator, whi...
if name in self: data = self[name] return data["accelerator"](**data["init_params"]) if default is not None: return default err_msg = "'{}' not found in registry. Available names: {}" available_names = self.available_accelerators() raise KeyE...
"""Calls the registered accelerator with the required parameters and returns the accelerator object. Args: name (str): the name that identifies a accelerator, e.g. "gpu" """ if name in self: data = self[name] return data["accelerator"](**data["init_p...
32
797
112
909
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,135
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/loggers/csv_logs.py
109,112
33,193
log_dir
CSVLogger
118,122
112,122
class CSVLogger(Logger): r"""Log to the local file system in CSV format. Logs are saved to ``os.path.join(root_dir, name, version)``. Args: root_dir: The root directory in which all your experiments with different names and versions will be stored. name: Experiment name. Defaults to ``'lig...
class CSVLogger(Logger): r"""Log to the local file system in CSV format. Logs are saved to ``os.path.join(root_dir, name, version)``. Args: root_dir: The root directory in which all your experiments with different names and versions will be stored. name: Experiment name. Defaults to ``'lig...
# create a pseudo standard path version = self.version if isinstance(self.version, str) else f"version_{self.version}" return os.path.join(self._root_dir, self.name, version)
"""The log directory for this run. By default, it is named ``'version_${self.version}'`` but it can be overridden by passing a string value for the constructor's version parameter instead of ``None`` or an int. """ # create a pseudo standard path version = self.version ...
18
1,541
60
1,601
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,136
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/loggers/csv_logs.py
229,230
193,275
save
_ExperimentWriter
231,250
230,250
class _ExperimentWriter: r"""Experiment writer for CSVLogger. Args: log_dir: Directory for the experiment logs """ NAME_METRICS_FILE = "metrics.csv" def __init__(self, log_dir: str) -> None: self.metrics: List[Dict[str, float]] = [] self.metrics_keys: List[str] = [] ...
class _ExperimentWriter: r"""Experiment writer for CSVLogger. Args: log_dir: Directory for the experiment logs """ NAME_METRICS_FILE = "metrics.csv" def __init__(self, log_dir: str) -> None: self.metrics: List[Dict[str, float]] = [] self.metrics_keys: List[str] = [] ...
if not self.metrics: return new_keys = self._record_new_keys() file_exists = self._fs.isfile(self.metrics_file_path) if new_keys and file_exists: # we need to re-write the file if the keys (header) change self._rewrite_with_new_header(self.metrics_ke...
"""Save recorded metrics into files.""" if not self.metrics: return new_keys = self._record_new_keys() file_exists = self._fs.isfile(self.metrics_file_path) if new_keys and file_exists: # we need to re-write the file if the keys (header) change ...
62
760
236
996
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,137
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/loggers/logger.py
102,103
1,138
rank_zero_experiment
104,123
103,123
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
@wraps(fn) def experiment(self: Logger) -> Union[Any, _DummyExperiment]: """ Note: ``self`` is a custom logger instance. The loggers typically wrap an ``experiment`` method with a ``@rank_zero_experiment`` decorator. ``Union[Any, _DummyExperiment]`` is used ...
"""Returns the real experiment on rank 0 and otherwise the _DummyExperiment.""" @wraps(fn) def experiment(self: Logger) -> Union[Any, _DummyExperiment]: """ Note: ``self`` is a custom logger instance. The loggers typically wrap an ``experiment`` method with a ``@rank...
69
1,055
201
1,256
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,138
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/loggers/logger.py
52,54
27,102
group_separator
Logger
55,57
54,57
class Logger(ABC): """Base class for experiment loggers.""" @property @abstractmethod def name(self) -> Optional[str]: """Return the experiment name.""" @property @abstractmethod def version(self) -> Optional[Union[int, str]]: """Return the experiment version.""" @prop...
class Logger(ABC): """Base class for experiment loggers.""" @property @abstractmethod def name(self) -> Optional[str]: """Return the experiment name.""" @property @abstractmethod def version(self) -> Optional[Union[int, str]]: """Return the experiment version.""" @prop...
return "/"
"""Return the default separator used by the logger to group the data into subfolders.""" return "/"
2
630
8
638
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Copyright The Lightning AI team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,139
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/plugins/collectives/collective.py
64,65
10,120
send
Collective
65,66
65,66
class Collective(ABC): """Interface for collective operations. Supports communications between multiple processes and multiple nodes. A collective owns a group. .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature which is still in development. """ def __init__(self)...
class Collective(ABC): """Interface for collective operations. Supports communications between multiple processes and multiple nodes. A collective owns a group. .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature which is still in development. """ def __init__(self)...
def send(self, tensor: Tensor, dst: int, tag: int = 0) -> None: ...
def send(self, tensor: Tensor, dst: int, tag: int = 0) -> None: ...
13
1,052
29
1,081
from abc import ABC, abstractmethod from typing import Any, List, Optional from torch import Tensor from typing_extensions import Self from lightning.fabric.utilities.types import CollectibleGroup class Collective(ABC): """Interface for collective operations. Supports communications between multiple proces...
from abc import ABC, abstractmethod from typing import Any, List, Optional from torch import Tensor from typing_extensions import Self from lightning.fabric.utilities.types import CollectibleGroup class Collective(ABC): """Interface for collective operations. Supports communications between multiple proces...
1,140
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning
/home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/plugins/collectives/single_device.py
79,82
10,108
is_available
SingleDeviceCollective
82,84
82,84
class SingleDeviceCollective(Collective): """Support for collective operations on a single device (no-op). .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature which is still in development. """ @property @override def rank(self) -> int: return 0 @pro...
class SingleDeviceCollective(Collective): """Support for collective operations on a single device (no-op). .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature which is still in development. """ @property @override def rank(self) -> int: return 0 @pro...
return True # vacuous truth
return True # vacuous truth
5
806
12
818
from typing import Any, List from torch import Tensor from typing_extensions import override from lightning.fabric.plugins.collectives.collective import Collective from lightning.fabric.utilities.types import CollectibleGroup class SingleDeviceCollective(Collective): """Support for collective operations on a si...
from typing import Any, List from torch import Tensor from typing_extensions import override from lightning.fabric.plugins.collectives.collective import Collective from lightning.fabric.utilities.types import CollectibleGroup class SingleDeviceCollective(Collective): """Support for collective operations on a si...