id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
155,271
from alpaca_turbo import Assistant from api_service.views_amm import AIModel from django.http import JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt ASSISTANT: Assistant = Assistant(AIModel.objects.first()) class Assistant: def __init__(self, auto_load=True, DEBUG=False) -> None: def reload(self): def get_bin_path(): def command(self): def prep_bot_input(self): def prep_model(self): def streamer( self, stuff_to_type, pre_recv_hook=None, post_recv_hook=None, ): def ask_bot(self, question, answer=""): def ask_bot_old(self, question, answer=""): def repl(debug=False): def load_model(request, uuid): global ASSISTANT ASSISTANT = Assistant(AIModel.objects.get(id=uuid)) res = ASSISTANT.load_model() return JsonResponse(res,safe=False)
null
155,272
from alpaca_turbo import Assistant from api_service.views_amm import AIModel from django.http import JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt ASSISTANT: Assistant = Assistant(AIModel.objects.first()) def unload_model(request): res = ASSISTANT.unload_model() return JsonResponse(res, safe=False)
null
155,273
from alpaca_turbo import Assistant from api_service.views_amm import AIModel from django.http import JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt ASSISTANT: Assistant = Assistant(AIModel.objects.first()) def stop_generation(request): res = ASSISTANT.stop_generation() return JsonResponse(res, safe=False)
null
155,274
from alpaca_turbo import Assistant from api_service.views_amm import AIModel from django.http import JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt ASSISTANT: Assistant = Assistant(AIModel.objects.first()) def new_chat(request): res = ASSISTANT.new_chat() return JsonResponse(res, safe=False)
null
155,275
from alpaca_turbo import Assistant from api_service.views_amm import AIModel from django.http import JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt ASSISTANT: Assistant = Assistant(AIModel.objects.first()) def remove_all_chat(request): res = ASSISTANT.remove_all_chat() return JsonResponse(res, safe=False)
null
155,276
from alpaca_turbo import Assistant from api_service.views_amm import AIModel from django.http import JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt ASSISTANT: Assistant = Assistant(AIModel.objects.first()) def load_chat(request, uuid): res = ASSISTANT.load_chat(uuid) return JsonResponse(res, safe=False)
null
155,277
from alpaca_turbo import Assistant from api_service.views_amm import AIModel from django.http import JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt ASSISTANT: Assistant = Assistant(AIModel.objects.first()) def get_conv_logs(request): res = ASSISTANT.get_conv_logs() return JsonResponse(res, safe=False)
null
155,278
from alpaca_turbo import Assistant from api_service.views_amm import AIModel from django.http import JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt ASSISTANT: Assistant = Assistant(AIModel.objects.first()) def remove_chat(request): res = ASSISTANT.remove_chat(uuid) return JsonResponse(res, safe=False)
null
155,279
from alpaca_turbo import Assistant from api_service.views_amm import AIModel from django.http import JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt ASSISTANT: Assistant = Assistant(AIModel.objects.first()) def clear_chat(request, uuid): res = ASSISTANT.clear_chat(uuid) return JsonResponse(res, safe=False)
null
155,280
from alpaca_turbo import Assistant from api_service.views_amm import AIModel from django.http import JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt ASSISTANT: Assistant = Assistant(AIModel.objects.first()) def safe_kill(request): res = ASSISTANT.safe_kill() return JsonResponse(res, safe=False)
null
155,281
from alpaca_turbo import Assistant from api_service.views_amm import AIModel from django.http import JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt ASSISTANT: Assistant = Assistant(AIModel.objects.first()) def status(request): res = {} res['status'] = ASSISTANT.current_state res['is_loaded'] = ASSISTANT.is_loaded res['threads'] = ASSISTANT.threads return JsonResponse(res, safe=False)
null
155,282
from chatbot.models import Conversation, Message from django.shortcuts import render from rest_framework import viewsets from .serializers import ConversationSerializer, MessageSerializer def index(request): return render(request, "chatbot/index.html")
null
155,283
from chatbot.models import Conversation, Message from django.shortcuts import render from rest_framework import viewsets from .serializers import ConversationSerializer, MessageSerializer def room(request, room_name): return render(request, "chatbot/room.html", {"room_name": room_name})
null
155,284
from typing import List, Optional, Union from pydantic import BaseModel from fastapi.responses import StreamingResponse, HTMLResponse from fastapi import FastAPI, Request from fastapi.templating import Jinja2Templates from alpaca_turbo import Assistant templates = Jinja2Templates(directory="templates") async def read_item(request: Request): return templates.TemplateResponse("index.html", {"request": request})
null
155,285
from typing import List, Optional, Union from pydantic import BaseModel from fastapi.responses import StreamingResponse, HTMLResponse from fastapi import FastAPI, Request from fastapi.templating import Jinja2Templates from alpaca_turbo import Assistant class CompletionRequest(BaseModel): model: Optional[str] prompt: Union[Communication, List[Message]] max_tokens: Optional[int] temperature: Optional[float] stop: Optional[Union[str, List[str]]] stream: Optional[bool] class CompletionResponseChoice(BaseModel): text: Communication finish_reason: Optional[str] class CompletionResponse(BaseModel): choices: List[CompletionResponseChoice] model = Model() def completion_token_generator(request: CompletionRequest): for token in model.get_completion_tokens(request.model, request.prompt, request.max_tokens, request.temperature, request.stop): completion_response = CompletionResponse( choices=[CompletionResponseChoice(text=token)]) yield f"data: {completion_response.json()}\n\n" async def completions(request: CompletionRequest): if request.stream: return StreamingResponse(completion_token_generator(request), media_type="text/event-stream") text = model.get_completion( request.model, request.prompt, request.max_tokens, request.temperature, request.stop) return CompletionResponse(choices=[CompletionResponseChoice(text=text)])
null
155,286
import os import urllib.request from rich.progress import Progress def clear_screen(): print("\033c")
null
155,287
import os import urllib.request from rich.progress import Progress def print_header(): print("") print(" / \ | |_ __ __ _ ___ __ _ |_ _| _ _ __| |__ ___ ") print(" / _ \ | | |_ \ / _` |/ __/ _` | | || | | | |__| |_ \ / _ \ ") print(" / ___ \| | |_) | (_| | (_| (_| | | || |_| | | | |_) | (_) |") print("/_/ \_\_| .__/ \__,_|\___\__,_| |_| \__,_|_| |_.__/ \___/ ") print(" |_| ") print("") print("") print("https://github.com/ViperX7/Alpaca-Turbo/") print("") print("") print("") print("")
null
155,288
import os import urllib.request from rich.progress import Progress def download_model(): url = "https://huggingface.co/Sosaka/Alpaca-native-4bit-ggml/resolve/main/ggml-alpaca-7b-q4.bin" filename = "ggml-alpaca-7b-q4.bin" if os.path.exists(filename): return choice = input("The model has not been downloaded. Would you like to download it now? (y/n)") if choice.lower() == "y": with Progress() as progress: task = progress.add_task("Downloading...", start=False) with urllib.request.urlopen(url) as response, open(filename, "wb") as out_file: file_size = int(response.headers.get("content-length", 0)) progress.update(task, total=file_size) progress.start_task(task) downloaded = 0 block_size = 8192 while True: buffer = response.read(block_size) if not buffer: break out_file.write(buffer) downloaded += len(buffer) progress.update(task, advance=len(buffer)) progress.remove_task(task) else: exit() def check_filesize(): filename = "ggml-alpaca-7b-q4.bin" filesize = os.path.getsize(filename) if filesize > 3221225472: return choice = input("The file size is less than or equal to 3GB. Do you want to redownload and delete the older file? (y/n)") if choice.lower() == "y": os.remove(filename) download_model() else: exit()
null
155,289
import json import logging import os import platform import signal import sys from time import sleep, time import psutil from interact import Process as process from rich import print as eprint from rich.logging import RichHandler from rich.progress import track class Assistant: """Alpaca Assistant""" model_path = "~/dalai/alpaca/models/7B/ggml-model-q4_0.bin" if "-m" not in sys.argv else sys.argv[-1] models = [] files = os.listdir() for file in files: if ".bin" in file: models.append(file) model_path = model_path if not models else models[0] def __init__(self, auto_load=True, DEBUG=False) -> None: self.DEBUG = "-d" in sys.argv self.seed = 888777 self.threads = 4 self.n_predict = 200 self.top_k = 40 self.top_p = 0.9 self.temp = 0.5 self.repeat_last_n = 64 self.repeat_penalty = 1.3 self.history_size = 1500 if platform.system() == "Windows": Assistant.model_path = os.path.expanduser(Assistant.model_path).replace( "/", "\\" ) else: Assistant.model_path = os.path.expanduser(Assistant.model_path) self.persona = "chat transcript between human and a bot named devil and the bot remembers everything from previous response" self.prompt = f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.""" self.format = ( """\n### Instruction:\n{instruction}\n\n### Response:\n{response}""" ) self.enable_history = False self.is_ready = False self.settings = AssistantSettings(self) self.end_marker = b"[end of text]" self.chat_history = [] self._killed=False try: self.settings.load() except: pass def reload(self): try: self._killed = True self.program.kill(signal.SIGTERM) sleep(2) except: pass self.is_ready = False self.prep_model() def get_bin_path(): if os.path.exists("bin/local"): return "bin/local" system_name = platform.system() if system_name == "Linux": name = "linux" elif system_name == "Windows": name = "win.exe" elif system_name == "Darwin": name = "mac" # elif system_name == "Android": # return "Android" else: exit() return os.path.join("bin", name) def command(self): command = [ Assistant.get_bin_path(), # "--color", # "-i", "--seed", f"{self.seed}", "-t", f"{self.threads}", "--top_k", f"{self.top_k}", "--top_p", f"{self.top_p}", "--repeat_last_n", f"{self.repeat_last_n}", "--repeat_penalty", f"{self.repeat_penalty}", "--n_predict", f"{self.n_predict}", "-m", f"{self.model_path}" , "--interactive-start", ] return command def prep_bot_input(self): """ prep_bot_input """ character = self.persona + "\n" + self.prompt history = self.chat_history if self.enable_history else [self.chat_history[-1]] prompt = "" for instr, resp in history: prompt += self.format.format(instruction=instr, response=resp) # prompt = prompt[-1*self.history_size:] if len(prompt) > self.history_size else prompt prompt = character + prompt prompt = prompt.strip("\n") prompt = prompt.replace("\n", "\\\n") print("======") print(prompt) print("======") return prompt def prep_model(self): if self.is_ready: return None _ = ( "" if os.path.exists(self.model_path) else print("Set the model path in settings") ) if not os.path.exists(self.model_path): return if os.path.exists("./pid"): try: with open("./pid") as file: pid = int(file.readline()) if psutil.pid_exists(pid): os.kill(pid, signal.SIGTERM) # os.remove("./pid") except (ProcessLookupError, FileNotFoundError): pass tstart = time() cmd = self.command _ = eprint(cmd) if self.DEBUG else None self.program = process(cmd, timeout=600) self._killed = False self.program.readline() self.program.recvuntil(b".") model_done = False for _ in track(range(40), "Loading Model"): data = self.program.recv(1).decode("utf-8") if not model_done else None model_done = True if data == "d" else model_done if model_done: continue self.program.recvuntil("\n") self.is_ready = True tend = time() eprint(f"Model Loaded in {(tend-tstart)} s") def streamer( self, stuff_to_type, pre_recv_hook=None, post_recv_hook=None, ): _ = self.prep_model() if not self.is_ready else None if not self.is_ready: raise FileNotFoundError( f"Cannot locate the specified model : {Assistant.model_path}\n Did you put the correct path in settings=>model_path?\n" ) self.program.recvuntil(">") opts = stuff_to_type.split("\n") for opt in opts: self.program.sendline(opt) while True: # _ = pre_recv_hook(self.program) if pre_recv_hook is not None else None if self._killed: return b"" yield self.program.recv(1) # _ = post_recv_hook(self.program) if pre_recv_hook is not None else None def ask_bot(self, question, answer=""): self.chat_history.append((question, answer)) inp_to_send = self.prep_bot_input() opt_stream = self.streamer(inp_to_send) tstart = time() buffer = b"" try: isfirst = True marker_detected = b"" char_old = b"" for char in opt_stream: buffer += char # update the buffer if isfirst: t_firstchar = time() wcount = len(question.replace("\n", " ").split(" ")) if self.DEBUG: eprint( f"Size of Input: {len(question)} chars || {wcount} words" ) eprint( f"Time taken to analyze the user input {t_firstchar-tstart} s" ) isfirst = False else: # Detect end of text if detected try to confirm else reset if char == b"[" or marker_detected: marker_detected += char if marker_detected in self.end_marker[: len(marker_detected)]: continue marker_detected = b"" if self.end_marker in buffer: buffer = buffer.replace(b"[end of text]", b"") tend = time() wcount = len(buffer.replace(b"\n", b" ").split(b" ")) if self.DEBUG == True: eprint( f"Size of output: {len(buffer)} chars || {wcount} words" ) eprint(f"Time taken to for generation {(tend-tstart)} s") break try: # Load the full buffer char = char_old + char # print single printable chars if len(char) == 1 and char[0] <= 0x7E and char[0] >= 0x21: char = char.decode("utf-8") char_old = b"" elif len(char) in [4, 6]: # If 4 byte code or 6 byte code char = char.decode("utf-8") char_old = b"" else: char_old = char continue except UnicodeDecodeError: char_old = char continue # print(char, end="") yield char except (KeyboardInterrupt, EOFError): print("Stooping") self.chat_history[-1] = (question, buffer.decode("utf-8").strip("\n")) return buffer def ask_bot_old(self, question, answer=""): """ run """ tend = 0 _ = self.prep_model() if not self.is_ready else None tstart = time() self.program.recvuntil(">") self.chat_history.append((question, answer)) opts = self.prep_bot_input.split("\n") for opt in opts: self.program.sendline(opt) data = None try: marker_detected = b"" char = self.program.recv(1) tfirstchar = time() wcount = len(question.replace("\n", " ").split(" ")) if self.DEBUG: eprint(f"Size of Input: {len(question)} chars || {wcount} words") eprint(f"Time taken to analyze the user input {(tfirstchar-tstart)} s") data = char yield char.decode("utf-8") while True: char = self.program.recv(1) data += char if char == b"[" or marker_detected: marker_detected += char if marker_detected in self.end_marker: continue marker_detected = b"" if self.end_marker in data: data = data.replace(b"[end of text]", b"") tend = time() wcount = len(data.replace(b"\n", b" ").split(b" ")) if self.DEBUG: eprint(f"Size of output: {len(data)} chars || {wcount} words") eprint(f"Time taken to for generation {(tend-tstart)} s") break yield char.decode("utf-8") except (KeyboardInterrupt, EOFError): print("Stooping") self.chat_history[-1] = (question, data.decode("utf-8").strip("\n")) return data def repl(debug=False): assistant = Assistant(DEBUG=debug) assistant.prep_model() while True: _ = eprint(assistant.chat_history) if debug else None resp = assistant.ask_bot(input(">>> "), "") for char in resp: print(char, end="") print() def health_checks(): FORMAT = "%(message)s" logging.basicConfig( level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()] ) log = logging.getLogger("rich") log.info("Running health checks ") test_assistant = Assistant(auto_load=False) # check if binary is available for system log.info("Checking for dependencies") if os.path.exists(Assistant.get_bin_path()): log.info("Found binary") else: log.fatal("Binary Not Found") log.info("Check https://github.com/ViperX7/alpaca.cpp") log.info("put the compiled file in (./bin/main or ./bin/main.exe )") exit() log.info("checking if system is supported") try: prog = process(Assistant.get_bin_path()) log.info("Supported system") except OSError: log.fatal("Binary Not supported on this system") log.info("Check https://github.com/ViperX7/alpaca.cpp") log.info("put the compiled file in (./bin/main or ./bin/main.exe )") exit() log.info("Looking for the models to load") if os.path.exists(os.path.expanduser(Assistant.model_path)): log.info(f"Found Model {Assistant.model_path}") sz = os.path.getsize(test_assistant.model_path) // (1024 * 1024) log.info(f"size of your model is {sz} MB (approx)") else: log.fatal( "model not found you need to download the models and set the model path in settings" ) if os.path.exists("./pid"): log.info("Other checks") log.fatal("Already running another instance or dirty exit last time") with open("./pid") as file: pid = int(file.readline()) log.info("Attempting to kill the process") try: os.kill(pid, signal.SIGTERM) except OSError: pass os.remove("./pid") log.info("Fixed the Issue Now Retry running") exit() memstat = psutil.virtual_memory() log.info("checking memory") log.info(f"Total memory {memstat.total//(1024*1024)} MB") log.info(f"Used memory {memstat.used//(1024*1024)} MB") log.info(f"Free memory {memstat.free//(1024*1024)} MB") exit() log.level = 5
null
155,290
import os import gradio as gr from alpaca_turbo import Assistant from prompts import History, Personas from rich import print as eprint def trunc(data): return data[: min(10, len(data))] if data else "<>" import urllib.request import os def quick_summary(data): for resp in data: return (trunc(resp[1]), None)
null
155,291
import os import gradio as gr from alpaca_turbo import Assistant from prompts import History, Personas from rich import print as eprint import urllib.request import os def download_file(url, file_path): with urllib.request.urlopen(url) as response: file_size = int(response.getheader('Content-Length')) with open(file_path, 'wb') as file: downloaded_size = 0 block_size = 8192 while True: buffer = response.read(block_size) if not buffer: break downloaded_size += len(buffer) file.write(buffer) status = f'{downloaded_size}/{file_size} bytes downloaded' print(status, end='\r') print()
null
155,292
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas def test_connect(): print("Socket connected")
null
155,293
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas def test_disconnect(): print("socket disconnected")
null
155,294
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas assistant = Assistant() def send_conv(data): print("-----------") print(data) print("-----------") inp = data["inp"] fmt = data.get("fmt", "") preprompt = data.get("pre", "") if "\n" not in fmt: fmt = fmt.replace("###","\n\n###") fmt = fmt.replace(":",":\n\n") fmt = fmt.strip("\n") output = assistant.send_conv(preprompt, fmt, inp) print("Attempting to GENERATE======================") buffer = "" for value in output: # (output, "Generating"): buffer += value emit("data", value) print("=====LOG=====") print(buffer) print("=====LOG=====")
null
155,295
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas assistant = Assistant() def remove_all_chat(): result = assistant.remove_all_chat() return jsonify({"result": result})
null
155,296
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas assistant = Assistant() def list_models(): models = assistant.list_available_models(assistant.models_directory) return jsonify(models)
null
155,297
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas assistant = Assistant() def unload_model(): result = assistant.safe_kill() return jsonify({"result": result}) def load_model(model_idx): assistant.model_idx = model_idx assistant.unload_model() resp = assistant.load_model() return jsonify({"status": resp})
null
155,298
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas assistant = Assistant() def stop(): res = assistant.stop_generation() return jsonify({"status": res})
null
155,299
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas assistant = Assistant() def status(): cpu_percent = psutil.cpu_percent() ram_usage = psutil.virtual_memory().percent total_ram = psutil.virtual_memory().total / (1024**3) # convert to GB total_cores = psutil.cpu_count(logical=False) total_threads = psutil.cpu_count(logical=True) # threads_above_80 = len( # [ # thread # for thread in psutil.process_iter(attrs=["pid", "name", "cpu_percent"]) # if thread.info["cpu_percent"] > 80 # ] # ) return jsonify( { "cpu_percent": cpu_percent, "ram_usage": ram_usage, "total_ram": total_ram, "total_cores": total_cores, "total_threads": total_threads, # "threads_above_80": threads_above_80, "is_model_loaded": assistant.is_loaded, "turbo_status": assistant.current_state, } )
null
155,300
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas assistant = Assistant() def get_config(): return jsonify( { "threads": assistant.threads, "top_k": assistant.top_k, "top_p": assistant.top_p, "temp": assistant.temp, "repeat_penalty": assistant.repeat_penalty, "seed": assistant.seed, "n_predict": assistant.n_predict, "repeat_last_n": assistant.repeat_last_n, "batch_size": assistant.batch_size, "antiprompt": assistant.antiprompt, "models_directory": assistant.models_directory, } )
null
155,301
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas assistant = Assistant() def set_config(): data = request.get_json() assistant.threads = data.get("threads", assistant.threads) assistant.top_k = data.get("top_k", assistant.top_k) assistant.top_p = data.get("top_p", assistant.top_p) assistant.temp = data.get("temp", assistant.temp) assistant.repeat_penalty = data.get("repeat_penalty", assistant.repeat_penalty) assistant.seed = data.get("seed", assistant.seed) assistant.n_predict = data.get("n_predict", assistant.n_predict) assistant.repeat_last_n = data.get("repeat_last_n", assistant.repeat_last_n) assistant.batch_size = data.get("batch_size", assistant.batch_size) assistant.antiprompt = data.get("antiprompt", assistant.antiprompt) assistant.models_directory = data.get("models_directory", assistant.models_directory) return jsonify({"success": True})
null
155,302
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas assistant = Assistant() def load_chat(id): result = assistant.load_chat(id) try: new_res = [res.to_json() for res in result] except AttributeError: new_res = result return jsonify(new_res)
null
155,303
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas assistant = Assistant() def save_chat(): result = assistant.save_chat() return jsonify(result)
null
155,304
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas assistant = Assistant() def get_conv_logs(): result = assistant.get_conv_logs() return jsonify(result)
null
155,305
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas assistant = Assistant() def clear_chat(): result = assistant.clear_chat() return jsonify(result)
null
155,306
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas personas = Personas("./prompts.json") def get_personas(): personas_list = personas.get_all() return jsonify(personas_list)
null
155,307
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas personas = Personas("./prompts.json") def get_persona(name): persona_data = personas.get(name) if persona_data: return jsonify(persona_data) else: return jsonify({"error": "Persona not found."})
null
155,308
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas personas = Personas("./prompts.json") def add_persona(): data = request.json if "name" not in data or "data" not in data: return jsonify({"error": "Name and data fields are required."}) name = data["name"] persona_data = data["data"] personas.add(name, persona_data) return jsonify({"success": True})
null
155,309
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas personas = Personas("./prompts.json") def update_persona(name): data = request.json persona_data = data["data"] personas.update(name, persona_data) return jsonify({"success": True})
null
155,310
import mimetypes import psutil from alpaca_turbo import Assistant from flask import Flask, jsonify, render_template, request from flask_cors import CORS from flask_socketio import SocketIO, emit from helpers.prompts import Personas def index(): return render_template("index.html")
null
155,311
import os import sys from signal import SIGINT, SIGTERM from colorama import Fore from pexpect.popen_spawn import PopenSpawn from rich import print as eprint def log(text): with open("./turbo.log", "a", encoding="utf-8") as file: file.write(text)
null
155,312
import json import os from rich import print as eprint class Conversation: """one interaction back and forth""" SAVE_DIR = "conversations" FILENAME_PREFIX = "chat" FILE_EXTENSION = "json" CONVERSATION_COUNTER = 0 def __init__( self, preprompt: str = "", fmt="", instruction: str = "", response: str = "", ): self.format = fmt #if isinstance(fmt, list) else [fmt] self.response = response self.instruction = instruction self.preprompt = preprompt def to_json(self): return { "format": self.format, "response": self.response, "instruction": self.instruction, "preprompt": self.preprompt, } def get_prompt(self): """Return the prompt filled with conversation""" convo = [] data = self.format.format(instruction=self.instruction, response=self.response) convo.append(data) return convo def save(conversations): # list["Conversation"]) -> None: """Save a list of conversations""" if not os.path.exists(Conversation.SAVE_DIR): os.makedirs(Conversation.SAVE_DIR) Conversation.CONVERSATION_COUNTER += 1 filename = f"{Conversation.FILENAME_PREFIX}{Conversation.CONVERSATION_COUNTER}.{Conversation.FILE_EXTENSION}" while os.path.exists(os.path.join(Conversation.SAVE_DIR, filename)): Conversation.CONVERSATION_COUNTER += 1 filename = f"{Conversation.FILENAME_PREFIX}{Conversation.CONVERSATION_COUNTER}.{Conversation.FILE_EXTENSION}" with open(os.path.join(Conversation.SAVE_DIR, filename), "w") as file: convo_list = [] for convo in conversations: convo_dict = convo.to_json() print("************") print(convo.to_json()) convo_list.append(convo_dict) json.dump(convo_list, file) def load(filename: str):# -> List[Conversation]: """Load a list of conversations from a file""" filepath = os.path.join(Conversation.SAVE_DIR, filename) with open(filepath, "r") as file: convo_list = json.load(file) conversations = [] for convo_data in convo_list: convo = Conversation( fmt=convo_data["format"], response=convo_data["response"], instruction=convo_data["instruction"], preprompt=convo_data["preprompt"], ) conversations.append(convo) return conversations def to_json_multi(conversations): # -> List[Dict[str, Union[str, List[str]]]]: """Convert a list of conversations into a JSON equivalent""" convo_list = [] for convo in conversations: convo_dict = convo.to_json() convo_list.append(convo_dict) return convo_list def remove_file(filename: str) -> None: """Remove a conversation file with the given name""" filepath = os.path.join(Conversation.SAVE_DIR, filename) os.remove(filepath) The provided code snippet includes necessary dependencies for implementing the `load_all_conversations` function. Write a Python function `def load_all_conversations()` to solve the following problem: Load all conversations from chat files in the conversations directory and map the file name to the conversation data Here is the function: def load_all_conversations():# -> Dict[str, List[Conversation]]: """Load all conversations from chat files in the conversations directory and map the file name to the conversation data""" conversations_dict = {} for filename in os.listdir(Conversation.SAVE_DIR): if filename.endswith(Conversation.FILE_EXTENSION): filepath = os.path.join(Conversation.SAVE_DIR, filename) conversations = Conversation.load(filename) conversations_dict[filename] = Conversation.to_json_multi(conversations) return conversations_dict
Load all conversations from chat files in the conversations directory and map the file name to the conversation data
155,313
import json import os from uuid import uuid4 import flet as ft from django.db import IntegrityError, models from utils.ui_elements import (SliderWithInput, easy_content_expander, get_random_color) def save_helper(obj: models.Model, objvar: str, value): print("hi") print(value) setattr(obj, objvar, value) # print(getattr(obj,objvar)) obj.save()
null
155,314
from os import name from time import time import flet as ft from alpaca_turbo import AIModel, Assistant, Conversation, Message from flet import * from flet import (ClipBehavior, Column, Container, CrossAxisAlignment, Image, ListTile, MainAxisAlignment, Markdown, OutlinedButton, Page, Row, Text, alignment, border, colors) from rich import print as eprint from utils.model_selector import model_selector from utils.status_widget import status_widget from utils.ui_elements import get_random_color The provided code snippet includes necessary dependencies for implementing the `choose_model` function. Write a Python function `def choose_model(index=None)` to solve the following problem: select model from available models or return None Returns: [TODO:return] Here is the function: def choose_model(index=None): """select model from available models or return None Returns: [TODO:return] """ models = AIModel.objects.all() if len(models) == 0: return None print("Available models:") for idx, model in enumerate(models): print(f"{idx+1}. {model.name}") index = int(input("Choose model: ")) - 1 if index is None else index if index < 0 or index >= len(models): return None return models[index] if index in range(0, len(models)) else None
select model from available models or return None Returns: [TODO:return]
155,315
import os import django import flet as ft from flet import * from flet import (ClipBehavior, Column, Container, CrossAxisAlignment, Image, ListTile, MainAxisAlignment, Markdown, OutlinedButton, Page, Row, Slider, Text, alignment, border, colors) from rich import print as eprint from ai_model_manager.models import AIModel, Prompt from utils.ui_elements import (easy_content_expander, get_random_color, put_center) def save_helper(obj, objvar: str, value): print("_-------") print(obj) print(objvar) print(value) print("_-------") setattr(obj, objvar, value) # print(getattr(obj,objvar)) obj.save()
null
155,316
import flet as ft import psutil cpu_percent = psutil.cpu_percent() ram_percent = psutil.virtual_memory().percent def status_widget(): stwid = ft.Container( ft.Column( alignment=ft.MainAxisAlignment.CENTER, horizontal_alignment=ft.CrossAxisAlignment.CENTER, controls=[ ft.Text("CPU"), ft.ProgressBar(width=400, color="blue", value=lambda:psutil.cpu_percent()//100), ft.Container(height=20), ft.Text("RAM"), ft.ProgressBar(width=400, color="blue", value=ram_percent/100), ], ), alignment=ft.alignment.center, height=160, bgcolor=ft.colors.BLUE_GREY, padding=20, ) return stwid
null
155,318
import flet as ft from ai_model_manager.models import Prompt, SliderWithInput from alpaca_turbo import AIModel, Assistant, Conversation, Message from utils.ui_elements import easy_content_expander, put_center def loading_progress(state): "add progress loader" return ft.Row( alignment=ft.MainAxisAlignment.CENTER, vertical_alignment=ft.CrossAxisAlignment.CENTER, controls=[ft.ProgressRing(), ft.Text("Loading model please wait ... ")] if state == "loading" else [ft.Icon(ft.icons.CHECK, color="green"), ft.Text("Model loaded")], ) class Prompt(models.Model): """Prompts for the AI model.""" id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255, default="New_Preset", blank=True, null=True) format = models.TextField( default="### Instruction:\n\n{instruction}\n\n### Response:\n\n{response}", blank=True, null=True, ) preprompt = models.TextField( default=" Below is an instruction that describes a task. Write a response that appropriately completes the request.", blank=True, null=True, ) antiprompt = models.TextField(default="### Human:", blank=True, null=True) is_preset = models.BooleanField(default=False) # use_bos = models.BooleanField(default=False) def __str__(self): return self.name def import_from_json(file_path): print(file_path) if isinstance(file_path, str): files_path = [file_path] else: files_path = file_path for file_path in files_path: with open(file_path, "r") as f: data = json.load(f) prompt = Prompt.objects.create( id=data["id"], name=data["name"], format=data["format"], preprompt=data["preprompt"], antiprompt=data["antiprompt"], is_preset=True, ) try: prompt.save() except IntegrityError: pass return len(files_path) def export_to_json(self): data = { "id": str(self.id), "name": self.name, "format": self.format, "preprompt": self.preprompt, "antiprompt": self.antiprompt, "is_preset": self.is_preset, } with open(f"prompt_{self.name}_{self.id}.json", "w") as f: json.dump(data, f) def get_ui(self, preset_mode=False): name = ft.Container( margin=ft.margin.only(bottom=50, top=10), padding=0, content=ft.TextField( value=self.name, bgcolor="#5587ff", label="Preset Name", multiline=False, on_change=lambda x: save_helper(self, "name", x.control.value), ), ) preprompt = ft.Container( margin=ft.margin.only(bottom=50, top=10), padding=0, content=ft.TextField( value=self.preprompt, bgcolor="#5587ff", label="Preprompt", multiline=True, min_lines=4, on_change=lambda x: save_helper(self, "preprompt", x.control.value), ), ) fmt = ft.Container( margin=ft.margin.only(bottom=50), padding=0, content=ft.TextField( value=self.format, bgcolor="#5587ff", label="Format", multiline=True, min_lines=7, on_change=lambda x: save_helper(self, "format", x.control.value), ), ) antiprompt = ft.Container( margin=ft.margin.only(bottom=50), padding=0, content=ft.TextField( value=self.antiprompt, bgcolor="#5587ff", label="Antiprompt", on_change=lambda x: save_helper(self, "antiprompt", x.control.value), ), ) preset_selector = ft.Container( margin=ft.margin.only(bottom=50, top=10), padding=0, content=ft.Dropdown( label="Load from Presets", options=[ ft.dropdown.Option(opt.id, opt.name) for opt in Prompt.objects.filter(is_preset=True) ], on_change=lambda x: [ setattr( preprompt.content, "value", Prompt.objects.filter(id=x.control.value).first().preprompt, ), setattr( fmt.content, "value", Prompt.objects.filter(id=x.control.value).first().format, ), setattr( antiprompt.content, "value", Prompt.objects.filter(id=x.control.value).first().antiprompt, ), save_helper(self, "preprompt", preprompt.content.value), save_helper(self, "format", fmt.content.value), save_helper(self, "antiprompt", antiprompt.content.value), preprompt.update(), fmt.update(), antiprompt.update(), ], ), ) selected_controls = [ name if preset_mode else preset_selector, preprompt, fmt, antiprompt, ] prompting_group = ft.Container( margin=ft.margin.only(top=10), padding=0, content=ft.Column( expand=True, scroll=True, alignment=ft.MainAxisAlignment.START, horizontal_alignment=ft.CrossAxisAlignment.START, spacing=10, controls=selected_controls, ), ) return prompting_group def ui_list_repr(self, refresh_call, prompt_settings): list_unit = ft.Container( bgcolor="#232343", content=ft.Row( controls=[ ft.Container( expand=True, content=ft.Row( controls=[ ft.Container( expand=True, content=ft.Text(self.name), ), ] ), ), ft.Container( # bgcolor=get_random_color(), content=ft.Row( controls=[ ft.IconButton( icon=ft.icons.UPLOAD, icon_color="blue", on_click=lambda _: self.export_to_json(), ), ft.IconButton( icon=ft.icons.DELETE, icon_color=ft.colors.RED_900, on_click=lambda x: [self.delete(), refresh_call()], ), ft.IconButton( icon=ft.icons.SETTINGS, icon_color=ft.colors.ORANGE_400, on_click=lambda _: prompt_settings(), ), ] ), border_radius=20, ), ] ), margin=0, padding=20, ) return list_unit class Assistant: """Alpaca Assistant""" model_path = "~/dalai/alpaca/models/7B/ggml-model-q4_0.bin" if "-m" not in sys.argv else sys.argv[-1] models = [] files = os.listdir() for file in files: if ".bin" in file: models.append(file) model_path = model_path if not models else models[0] def __init__(self, auto_load=True, DEBUG=False) -> None: self.DEBUG = "-d" in sys.argv self.seed = 888777 self.threads = 4 self.n_predict = 200 self.top_k = 40 self.top_p = 0.9 self.temp = 0.5 self.repeat_last_n = 64 self.repeat_penalty = 1.3 self.history_size = 1500 if platform.system() == "Windows": Assistant.model_path = os.path.expanduser(Assistant.model_path).replace( "/", "\\" ) else: Assistant.model_path = os.path.expanduser(Assistant.model_path) self.persona = "chat transcript between human and a bot named devil and the bot remembers everything from previous response" self.prompt = f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.""" self.format = ( """\n### Instruction:\n{instruction}\n\n### Response:\n{response}""" ) self.enable_history = False self.is_ready = False self.settings = AssistantSettings(self) self.end_marker = b"[end of text]" self.chat_history = [] self._killed=False try: self.settings.load() except: pass def reload(self): try: self._killed = True self.program.kill(signal.SIGTERM) sleep(2) except: pass self.is_ready = False self.prep_model() def get_bin_path(): if os.path.exists("bin/local"): return "bin/local" system_name = platform.system() if system_name == "Linux": name = "linux" elif system_name == "Windows": name = "win.exe" elif system_name == "Darwin": name = "mac" # elif system_name == "Android": # return "Android" else: exit() return os.path.join("bin", name) def command(self): command = [ Assistant.get_bin_path(), # "--color", # "-i", "--seed", f"{self.seed}", "-t", f"{self.threads}", "--top_k", f"{self.top_k}", "--top_p", f"{self.top_p}", "--repeat_last_n", f"{self.repeat_last_n}", "--repeat_penalty", f"{self.repeat_penalty}", "--n_predict", f"{self.n_predict}", "-m", f"{self.model_path}" , "--interactive-start", ] return command def prep_bot_input(self): """ prep_bot_input """ character = self.persona + "\n" + self.prompt history = self.chat_history if self.enable_history else [self.chat_history[-1]] prompt = "" for instr, resp in history: prompt += self.format.format(instruction=instr, response=resp) # prompt = prompt[-1*self.history_size:] if len(prompt) > self.history_size else prompt prompt = character + prompt prompt = prompt.strip("\n") prompt = prompt.replace("\n", "\\\n") print("======") print(prompt) print("======") return prompt def prep_model(self): if self.is_ready: return None _ = ( "" if os.path.exists(self.model_path) else print("Set the model path in settings") ) if not os.path.exists(self.model_path): return if os.path.exists("./pid"): try: with open("./pid") as file: pid = int(file.readline()) if psutil.pid_exists(pid): os.kill(pid, signal.SIGTERM) # os.remove("./pid") except (ProcessLookupError, FileNotFoundError): pass tstart = time() cmd = self.command _ = eprint(cmd) if self.DEBUG else None self.program = process(cmd, timeout=600) self._killed = False self.program.readline() self.program.recvuntil(b".") model_done = False for _ in track(range(40), "Loading Model"): data = self.program.recv(1).decode("utf-8") if not model_done else None model_done = True if data == "d" else model_done if model_done: continue self.program.recvuntil("\n") self.is_ready = True tend = time() eprint(f"Model Loaded in {(tend-tstart)} s") def streamer( self, stuff_to_type, pre_recv_hook=None, post_recv_hook=None, ): _ = self.prep_model() if not self.is_ready else None if not self.is_ready: raise FileNotFoundError( f"Cannot locate the specified model : {Assistant.model_path}\n Did you put the correct path in settings=>model_path?\n" ) self.program.recvuntil(">") opts = stuff_to_type.split("\n") for opt in opts: self.program.sendline(opt) while True: # _ = pre_recv_hook(self.program) if pre_recv_hook is not None else None if self._killed: return b"" yield self.program.recv(1) # _ = post_recv_hook(self.program) if pre_recv_hook is not None else None def ask_bot(self, question, answer=""): self.chat_history.append((question, answer)) inp_to_send = self.prep_bot_input() opt_stream = self.streamer(inp_to_send) tstart = time() buffer = b"" try: isfirst = True marker_detected = b"" char_old = b"" for char in opt_stream: buffer += char # update the buffer if isfirst: t_firstchar = time() wcount = len(question.replace("\n", " ").split(" ")) if self.DEBUG: eprint( f"Size of Input: {len(question)} chars || {wcount} words" ) eprint( f"Time taken to analyze the user input {t_firstchar-tstart} s" ) isfirst = False else: # Detect end of text if detected try to confirm else reset if char == b"[" or marker_detected: marker_detected += char if marker_detected in self.end_marker[: len(marker_detected)]: continue marker_detected = b"" if self.end_marker in buffer: buffer = buffer.replace(b"[end of text]", b"") tend = time() wcount = len(buffer.replace(b"\n", b" ").split(b" ")) if self.DEBUG == True: eprint( f"Size of output: {len(buffer)} chars || {wcount} words" ) eprint(f"Time taken to for generation {(tend-tstart)} s") break try: # Load the full buffer char = char_old + char # print single printable chars if len(char) == 1 and char[0] <= 0x7E and char[0] >= 0x21: char = char.decode("utf-8") char_old = b"" elif len(char) in [4, 6]: # If 4 byte code or 6 byte code char = char.decode("utf-8") char_old = b"" else: char_old = char continue except UnicodeDecodeError: char_old = char continue # print(char, end="") yield char except (KeyboardInterrupt, EOFError): print("Stooping") self.chat_history[-1] = (question, buffer.decode("utf-8").strip("\n")) return buffer def ask_bot_old(self, question, answer=""): """ run """ tend = 0 _ = self.prep_model() if not self.is_ready else None tstart = time() self.program.recvuntil(">") self.chat_history.append((question, answer)) opts = self.prep_bot_input.split("\n") for opt in opts: self.program.sendline(opt) data = None try: marker_detected = b"" char = self.program.recv(1) tfirstchar = time() wcount = len(question.replace("\n", " ").split(" ")) if self.DEBUG: eprint(f"Size of Input: {len(question)} chars || {wcount} words") eprint(f"Time taken to analyze the user input {(tfirstchar-tstart)} s") data = char yield char.decode("utf-8") while True: char = self.program.recv(1) data += char if char == b"[" or marker_detected: marker_detected += char if marker_detected in self.end_marker: continue marker_detected = b"" if self.end_marker in data: data = data.replace(b"[end of text]", b"") tend = time() wcount = len(data.replace(b"\n", b" ").split(b" ")) if self.DEBUG: eprint(f"Size of output: {len(data)} chars || {wcount} words") eprint(f"Time taken to for generation {(tend-tstart)} s") break yield char.decode("utf-8") except (KeyboardInterrupt, EOFError): print("Stooping") self.chat_history[-1] = (question, data.decode("utf-8").strip("\n")) return data def repl(debug=False): assistant = Assistant(DEBUG=debug) assistant.prep_model() while True: _ = eprint(assistant.chat_history) if debug else None resp = assistant.ask_bot(input(">>> "), "") for char in resp: print(char, end="") print() def put_center(content,bgcolor=None): bgcolor = bgcolor if bgcolor else get_random_color() ui = Container( margin=0, padding=0, bgcolor=bgcolor, alignment=ft.alignment.center, content=Row( expand=True, alignment=MainAxisAlignment.CENTER, vertical_alignment=CrossAxisAlignment.CENTER, controls=[ Container( expand=True, alignment=ft.alignment.center, bgcolor=bgcolor, clip_behavior=ClipBehavior.HARD_EDGE, content=content, ) ], ), ) return ui The provided code snippet includes necessary dependencies for implementing the `model_selector` function. Write a Python function `def model_selector(assistant: Assistant, callback=lambda: None)` to solve the following problem: Model loading UI Here is the function: def model_selector(assistant: Assistant, callback=lambda: None): """Model loading UI""" model_options = [ ft.dropdown.Option(model.id, model.name) for model in AIModel.objects.all() ] prompt_options = [ ft.dropdown.Option(prompt.id, prompt.name) for prompt in Prompt.objects.filter(is_preset=True) ] prompt_selector = ft.Container( width=500, bgcolor=ft.colors.BLUE_GREY, content=ft.Dropdown( width=500, hint_text="Use Model Default", options=prompt_options, # value=prompt_options[0].key, on_change=lambda x: [ setattr( assistant, "prompt", Prompt.objects.filter(id=x.control.value).first(), ), model_selection_screen.update(), ], ), ) if len(model_options) == 0: model_selection_screen = put_center( ft.Text( "No Models can be located. Please Import models from settings", ) ) else: model_selection_screen = ft.Container( bgcolor="#112233", expand=True, content=ft.Column( alignment=ft.MainAxisAlignment.SPACE_EVENLY, horizontal_alignment=ft.CrossAxisAlignment.CENTER, controls=[ prompt_selector, ft.Container( alignment=ft.alignment.center, # bgcolor="blue", content=ft.Row( alignment=ft.MainAxisAlignment.CENTER, vertical_alignment=ft.CrossAxisAlignment.CENTER, controls=[ ft.Dropdown( width=500, # label="Model", # hint_text="Select model", options=model_options, value=model_options[0].key, on_change=lambda x: [ model_selection_screen.content.controls.pop() if len(model_selection_screen.content.controls) > 1 else None, setattr( assistant, "model", AIModel.objects.filter( id=x.control.value ).first(), ), model_selection_screen.content.controls.append( loading_progress("loading") ), model_selection_screen.update(), assistant.load_model(), model_selection_screen.content.controls.pop(), model_selection_screen.content.controls.append( loading_progress("loaded") ), callback(), model_selection_screen.update(), ], ), ft.IconButton( icon=ft.icons.SETTINGS, ), ], ), ), ft.Container( width=500, alignment=ft.alignment.center, content=SliderWithInput( label="Threads", min=1, max=8, divisions=7, value=4, callback=lambda x: setattr(assistant, "threads", x), ).getui(), ), ], ), ) return model_selection_screen
Model loading UI
155,319
import flet as ft from flet import * import random def get_random_color(): color = "#" + "".join([random.choice("0123456789ABCDEF") for _ in range(6)]) return color The provided code snippet includes necessary dependencies for implementing the `easy_content_expander` function. Write a Python function `def easy_content_expander(content, vexpand=True, hexpand=True, bgcolor=None)` to solve the following problem: Simple function to expand stuff Here is the function: def easy_content_expander(content, vexpand=True, hexpand=True, bgcolor=None): """Simple function to expand stuff""" obj = Row( expand=vexpand, controls=[ Container( bgcolor=bgcolor if bgcolor else get_random_color(), expand=hexpand, content=Column(controls=[content]), padding=ft.padding.only(top=20, bottom=20, left=20, right=20), margin=0, ) ], ) return obj
Simple function to expand stuff
155,320
import easing_functions as ef import random import torch from torchvision import transforms from torchvision.transforms import functional as F def lerp(a, b, percentage): return a * (1 - percentage) + b * percentage
null
155,321
import easing_functions as ef import random import torch from torchvision import transforms from torchvision.transforms import functional as F class Step: # Custom easing function for sudden change. def __call__(self, value): return 0 if value < 0.5 else 1 def random_easing_fn(): if random.random() < 0.2: return ef.LinearInOut() else: return random.choice([ ef.BackEaseIn, ef.BackEaseOut, ef.BackEaseInOut, ef.BounceEaseIn, ef.BounceEaseOut, ef.BounceEaseInOut, ef.CircularEaseIn, ef.CircularEaseOut, ef.CircularEaseInOut, ef.CubicEaseIn, ef.CubicEaseOut, ef.CubicEaseInOut, ef.ExponentialEaseIn, ef.ExponentialEaseOut, ef.ExponentialEaseInOut, ef.ElasticEaseIn, ef.ElasticEaseOut, ef.ElasticEaseInOut, ef.QuadEaseIn, ef.QuadEaseOut, ef.QuadEaseInOut, ef.QuarticEaseIn, ef.QuarticEaseOut, ef.QuarticEaseInOut, ef.QuinticEaseIn, ef.QuinticEaseOut, ef.QuinticEaseInOut, ef.SineEaseIn, ef.SineEaseOut, ef.SineEaseInOut, Step, ])()
null
155,322
import argparse import os import pims import numpy as np import random from PIL import Image from tqdm import tqdm from tqdm.contrib.concurrent import process_map from torchvision import transforms from torchvision.transforms import functional as F args = parser.parse_args() imagematte_filenames = os.listdir(os.path.join(args.imagematte_dir, 'fgr')) background_filenames = os.listdir(args.background_dir) def motion_affine(*imgs): config = dict(degrees=(-10, 10), translate=(0.1, 0.1), scale_ranges=(0.9, 1.1), shears=(-5, 5), img_size=imgs[0][0].size) angleA, (transXA, transYA), scaleA, (shearXA, shearYA) = transforms.RandomAffine.get_params(**config) angleB, (transXB, transYB), scaleB, (shearXB, shearYB) = transforms.RandomAffine.get_params(**config) T = len(imgs[0]) variation_over_time = random.random() for t in range(T): percentage = (t / (T - 1)) * variation_over_time angle = lerp(angleA, angleB, percentage) transX = lerp(transXA, transXB, percentage) transY = lerp(transYA, transYB, percentage) scale = lerp(scaleA, scaleB, percentage) shearX = lerp(shearXA, shearXB, percentage) shearY = lerp(shearYA, shearYB, percentage) for img in imgs: img[t] = F.affine(img[t], angle, (transX, transY), scale, (shearX, shearY), F.InterpolationMode.BILINEAR) return imgs def process(i): imagematte_filename = imagematte_filenames[i % len(imagematte_filenames)] background_filename = background_filenames[i % len(background_filenames)] out_path = os.path.join(args.out_dir, str(i).zfill(4)) os.makedirs(os.path.join(out_path, 'fgr'), exist_ok=True) os.makedirs(os.path.join(out_path, 'pha'), exist_ok=True) os.makedirs(os.path.join(out_path, 'com'), exist_ok=True) os.makedirs(os.path.join(out_path, 'bgr'), exist_ok=True) with Image.open(os.path.join(args.background_dir, background_filename)) as bgr: bgr = bgr.convert('RGB') w, h = bgr.size scale = args.resolution / min(h, w) w, h = int(w * scale), int(h * scale) bgr = bgr.resize((w, h)) bgr = F.center_crop(bgr, (args.resolution, args.resolution)) with Image.open(os.path.join(args.imagematte_dir, 'fgr', imagematte_filename)) as fgr, \ Image.open(os.path.join(args.imagematte_dir, 'pha', imagematte_filename)) as pha: fgr = fgr.convert('RGB') pha = pha.convert('L') fgrs = [fgr] * args.num_frames phas = [pha] * args.num_frames fgrs, phas = motion_affine(fgrs, phas) for t in tqdm(range(args.num_frames), desc=str(i).zfill(4)): fgr = fgrs[t] pha = phas[t] w, h = fgr.size scale = args.resolution / max(h, w) w, h = int(w * scale), int(h * scale) fgr = fgr.resize((w, h)) pha = pha.resize((w, h)) if h < args.resolution: pt = (args.resolution - h) // 2 pb = args.resolution - h - pt else: pt = 0 pb = 0 if w < args.resolution: pl = (args.resolution - w) // 2 pr = args.resolution - w - pl else: pl = 0 pr = 0 fgr = F.pad(fgr, [pl, pt, pr, pb]) pha = F.pad(pha, [pl, pt, pr, pb]) if i // len(imagematte_filenames) % 2 == 1: fgr = fgr.transpose(Image.FLIP_LEFT_RIGHT) pha = pha.transpose(Image.FLIP_LEFT_RIGHT) fgr.save(os.path.join(out_path, 'fgr', str(t).zfill(4) + args.extension)) pha.save(os.path.join(out_path, 'pha', str(t).zfill(4) + args.extension)) if t == 0: bgr.save(os.path.join(out_path, 'bgr', str(t).zfill(4) + args.extension)) else: os.symlink(str(0).zfill(4) + args.extension, os.path.join(out_path, 'bgr', str(t).zfill(4) + args.extension)) pha = np.asarray(pha).astype(float)[:, :, None] / 255 com = Image.fromarray(np.uint8(np.asarray(fgr) * pha + np.asarray(bgr) * (1 - pha))) com.save(os.path.join(out_path, 'com', str(t).zfill(4) + args.extension))
null
155,323
import argparse import os import pims import numpy as np import random from multiprocessing import Pool from PIL import Image from tqdm.contrib.concurrent import process_map from torchvision import transforms from torchvision.transforms import functional as F args = parser.parse_args() imagematte_filenames = os.listdir(os.path.join(args.imagematte_dir, 'fgr')) background_filenames = [ "0000.mp4", "0007.mp4", "0008.mp4", "0010.mp4", "0013.mp4", "0015.mp4", "0016.mp4", "0018.mp4", "0021.mp4", "0029.mp4", "0033.mp4", "0035.mp4", "0039.mp4", "0050.mp4", "0052.mp4", "0055.mp4", "0060.mp4", "0063.mp4", "0087.mp4", "0086.mp4", "0090.mp4", "0101.mp4", "0110.mp4", "0117.mp4", "0120.mp4", "0122.mp4", "0123.mp4", "0125.mp4", "0128.mp4", "0131.mp4", "0172.mp4", "0176.mp4", "0181.mp4", "0187.mp4", "0193.mp4", "0198.mp4", "0220.mp4", "0221.mp4", "0224.mp4", "0229.mp4", "0233.mp4", "0238.mp4", "0241.mp4", "0245.mp4", "0246.mp4" ] def motion_affine(*imgs): config = dict(degrees=(-10, 10), translate=(0.1, 0.1), scale_ranges=(0.9, 1.1), shears=(-5, 5), img_size=imgs[0][0].size) angleA, (transXA, transYA), scaleA, (shearXA, shearYA) = transforms.RandomAffine.get_params(**config) angleB, (transXB, transYB), scaleB, (shearXB, shearYB) = transforms.RandomAffine.get_params(**config) T = len(imgs[0]) variation_over_time = random.random() for t in range(T): percentage = (t / (T - 1)) * variation_over_time angle = lerp(angleA, angleB, percentage) transX = lerp(transXA, transXB, percentage) transY = lerp(transYA, transYB, percentage) scale = lerp(scaleA, scaleB, percentage) shearX = lerp(shearXA, shearXB, percentage) shearY = lerp(shearYA, shearYB, percentage) for img in imgs: img[t] = F.affine(img[t], angle, (transX, transY), scale, (shearX, shearY), F.InterpolationMode.BILINEAR) return imgs def process(i): imagematte_filename = imagematte_filenames[i % len(imagematte_filenames)] background_filename = background_filenames[i % len(background_filenames)] bgrs = pims.PyAVVideoReader(os.path.join(args.background_dir, background_filename)) out_path = os.path.join(args.out_dir, str(i).zfill(4)) os.makedirs(os.path.join(out_path, 'fgr'), exist_ok=True) os.makedirs(os.path.join(out_path, 'pha'), exist_ok=True) os.makedirs(os.path.join(out_path, 'com'), exist_ok=True) os.makedirs(os.path.join(out_path, 'bgr'), exist_ok=True) with Image.open(os.path.join(args.imagematte_dir, 'fgr', imagematte_filename)) as fgr, \ Image.open(os.path.join(args.imagematte_dir, 'pha', imagematte_filename)) as pha: fgr = fgr.convert('RGB') pha = pha.convert('L') fgrs = [fgr] * args.num_frames phas = [pha] * args.num_frames fgrs, phas = motion_affine(fgrs, phas) for t in range(args.num_frames): fgr = fgrs[t] pha = phas[t] w, h = fgr.size scale = args.resolution / max(h, w) w, h = int(w * scale), int(h * scale) fgr = fgr.resize((w, h)) pha = pha.resize((w, h)) if h < args.resolution: pt = (args.resolution - h) // 2 pb = args.resolution - h - pt else: pt = 0 pb = 0 if w < args.resolution: pl = (args.resolution - w) // 2 pr = args.resolution - w - pl else: pl = 0 pr = 0 fgr = F.pad(fgr, [pl, pt, pr, pb]) pha = F.pad(pha, [pl, pt, pr, pb]) if i // len(imagematte_filenames) % 2 == 1: fgr = fgr.transpose(Image.FLIP_LEFT_RIGHT) pha = pha.transpose(Image.FLIP_LEFT_RIGHT) fgr.save(os.path.join(out_path, 'fgr', str(t).zfill(4) + args.extension)) pha.save(os.path.join(out_path, 'pha', str(t).zfill(4) + args.extension)) bgr = Image.fromarray(bgrs[t]).convert('RGB') w, h = bgr.size scale = args.resolution / min(h, w) w, h = int(w * scale), int(h * scale) bgr = bgr.resize((w, h)) bgr = F.center_crop(bgr, (args.resolution, args.resolution)) bgr.save(os.path.join(out_path, 'bgr', str(t).zfill(4) + args.extension)) pha = np.asarray(pha).astype(float)[:, :, None] / 255 com = Image.fromarray(np.uint8(np.asarray(fgr) * pha + np.asarray(bgr) * (1 - pha))) com.save(os.path.join(out_path, 'com', str(t).zfill(4) + args.extension))
null
155,324
import torch from model import MattingNetwork def mobilenetv3(pretrained: bool = True, progress: bool = True): model = MattingNetwork('mobilenetv3') if pretrained: url = 'https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3.pth' model.load_state_dict(torch.hub.load_state_dict_from_url(url, map_location='cpu', progress=progress)) return model
null
155,325
import torch from model import MattingNetwork def resnet50(pretrained: bool = True, progress: bool = True): model = MattingNetwork('resnet50') if pretrained: url = 'https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_resnet50.pth' model.load_state_dict(torch.hub.load_state_dict_from_url(url, map_location='cpu', progress=progress)) return model
null
155,326
import torch from model import MattingNetwork def convert_video(model, input_source: str, input_resize: Optional[Tuple[int, int]] = None, downsample_ratio: Optional[float] = None, output_type: str = 'video', output_composition: Optional[str] = None, output_alpha: Optional[str] = None, output_foreground: Optional[str] = None, output_video_mbps: Optional[float] = None, seq_chunk: int = 1, num_workers: int = 0, progress: bool = True, device: Optional[str] = None, dtype: Optional[torch.dtype] = None): """ Args: input_source:A video file, or an image sequence directory. Images must be sorted in accending order, support png and jpg. input_resize: If provided, the input are first resized to (w, h). downsample_ratio: The model's downsample_ratio hyperparameter. If not provided, model automatically set one. output_type: Options: ["video", "png_sequence"]. output_composition: The composition output path. File path if output_type == 'video'. Directory path if output_type == 'png_sequence'. If output_type == 'video', the composition has green screen background. If output_type == 'png_sequence'. the composition is RGBA png images. output_alpha: The alpha output from the model. output_foreground: The foreground output from the model. seq_chunk: Number of frames to process at once. Increase it for better parallelism. num_workers: PyTorch's DataLoader workers. Only use >0 for image input. progress: Show progress bar. device: Only need to manually provide if model is a TorchScript freezed model. dtype: Only need to manually provide if model is a TorchScript freezed model. """ assert downsample_ratio is None or (downsample_ratio > 0 and downsample_ratio <= 1), 'Downsample ratio must be between 0 (exclusive) and 1 (inclusive).' assert any([output_composition, output_alpha, output_foreground]), 'Must provide at least one output.' assert output_type in ['video', 'png_sequence'], 'Only support "video" and "png_sequence" output modes.' assert seq_chunk >= 1, 'Sequence chunk must be >= 1' assert num_workers >= 0, 'Number of workers must be >= 0' # Initialize transform if input_resize is not None: transform = transforms.Compose([ transforms.Resize(input_resize[::-1]), transforms.ToTensor() ]) else: transform = transforms.ToTensor() # Initialize reader if os.path.isfile(input_source): source = VideoReader(input_source, transform) else: source = ImageSequenceReader(input_source, transform) reader = DataLoader(source, batch_size=seq_chunk, pin_memory=True, num_workers=num_workers) # Initialize writers if output_type == 'video': frame_rate = source.frame_rate if isinstance(source, VideoReader) else 30 output_video_mbps = 1 if output_video_mbps is None else output_video_mbps if output_composition is not None: writer_com = VideoWriter( path=output_composition, frame_rate=frame_rate, bit_rate=int(output_video_mbps * 1000000)) if output_alpha is not None: writer_pha = VideoWriter( path=output_alpha, frame_rate=frame_rate, bit_rate=int(output_video_mbps * 1000000)) if output_foreground is not None: writer_fgr = VideoWriter( path=output_foreground, frame_rate=frame_rate, bit_rate=int(output_video_mbps * 1000000)) else: if output_composition is not None: writer_com = ImageSequenceWriter(output_composition, 'png') if output_alpha is not None: writer_pha = ImageSequenceWriter(output_alpha, 'png') if output_foreground is not None: writer_fgr = ImageSequenceWriter(output_foreground, 'png') # Inference model = model.eval() if device is None or dtype is None: param = next(model.parameters()) dtype = param.dtype device = param.device if (output_composition is not None) and (output_type == 'video'): bgr = torch.tensor([120, 255, 155], device=device, dtype=dtype).div(255).view(1, 1, 3, 1, 1) try: with torch.no_grad(): bar = tqdm(total=len(source), disable=not progress, dynamic_ncols=True) rec = [None] * 4 for src in reader: if downsample_ratio is None: downsample_ratio = auto_downsample_ratio(*src.shape[2:]) src = src.to(device, dtype, non_blocking=True).unsqueeze(0) # [B, T, C, H, W] fgr, pha, *rec = model(src, *rec, downsample_ratio) if output_foreground is not None: writer_fgr.write(fgr[0]) if output_alpha is not None: writer_pha.write(pha[0]) if output_composition is not None: if output_type == 'video': com = fgr * pha + bgr * (1 - pha) else: fgr = fgr * pha.gt(0) com = torch.cat([fgr, pha], dim=-3) writer_com.write(com[0]) bar.update(src.size(1)) finally: # Clean up if output_composition is not None: writer_com.close() if output_alpha is not None: writer_pha.close() if output_foreground is not None: writer_fgr.close() def converter(): try: from inference import convert_video return convert_video except ModuleNotFoundError as error: print(error) print('Please run "pip install av tqdm pims"')
null
155,327
import torch from torch.nn import functional as F def laplacian_loss(pred, true, max_levels=5): kernel = gauss_kernel(device=pred.device, dtype=pred.dtype) pred_pyramid = laplacian_pyramid(pred, kernel, max_levels) true_pyramid = laplacian_pyramid(true, kernel, max_levels) loss = 0 for level in range(max_levels): loss += (2 ** level) * F.l1_loss(pred_pyramid[level], true_pyramid[level]) return loss / max_levels The provided code snippet includes necessary dependencies for implementing the `matting_loss` function. Write a Python function `def matting_loss(pred_fgr, pred_pha, true_fgr, true_pha)` to solve the following problem: Args: pred_fgr: Shape(B, T, 3, H, W) pred_pha: Shape(B, T, 1, H, W) true_fgr: Shape(B, T, 3, H, W) true_pha: Shape(B, T, 1, H, W) Here is the function: def matting_loss(pred_fgr, pred_pha, true_fgr, true_pha): """ Args: pred_fgr: Shape(B, T, 3, H, W) pred_pha: Shape(B, T, 1, H, W) true_fgr: Shape(B, T, 3, H, W) true_pha: Shape(B, T, 1, H, W) """ loss = dict() # Alpha losses loss['pha_l1'] = F.l1_loss(pred_pha, true_pha) loss['pha_laplacian'] = laplacian_loss(pred_pha.flatten(0, 1), true_pha.flatten(0, 1)) loss['pha_coherence'] = F.mse_loss(pred_pha[:, 1:] - pred_pha[:, :-1], true_pha[:, 1:] - true_pha[:, :-1]) * 5 # Foreground losses true_msk = true_pha.gt(0) pred_fgr = pred_fgr * true_msk true_fgr = true_fgr * true_msk loss['fgr_l1'] = F.l1_loss(pred_fgr, true_fgr) loss['fgr_coherence'] = F.mse_loss(pred_fgr[:, 1:] - pred_fgr[:, :-1], true_fgr[:, 1:] - true_fgr[:, :-1]) * 5 # Total loss['total'] = loss['pha_l1'] + loss['pha_coherence'] + loss['pha_laplacian'] \ + loss['fgr_l1'] + loss['fgr_coherence'] return loss
Args: pred_fgr: Shape(B, T, 3, H, W) pred_pha: Shape(B, T, 1, H, W) true_fgr: Shape(B, T, 3, H, W) true_pha: Shape(B, T, 1, H, W)
155,328
import torch from torch.nn import functional as F The provided code snippet includes necessary dependencies for implementing the `segmentation_loss` function. Write a Python function `def segmentation_loss(pred_seg, true_seg)` to solve the following problem: Args: pred_seg: Shape(B, T, 1, H, W) true_seg: Shape(B, T, 1, H, W) Here is the function: def segmentation_loss(pred_seg, true_seg): """ Args: pred_seg: Shape(B, T, 1, H, W) true_seg: Shape(B, T, 1, H, W) """ return F.binary_cross_entropy_with_logits(pred_seg, true_seg)
Args: pred_seg: Shape(B, T, 1, H, W) true_seg: Shape(B, T, 1, H, W)
155,329
import os import platform import sys import pkg_resources import torch def info_system() -> dict: return { "OS": platform.system(), "architecture": platform.architecture(), "version": platform.version(), "release": platform.release(), "processor": platform.processor(), "python": platform.python_version(), }
null
155,330
import os import platform import sys import pkg_resources import torch def info_cuda() -> dict: return { "GPU": [torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())] or None, "available": torch.cuda.is_available(), "version": torch.version.cuda, }
null
155,331
import os import platform import sys import pkg_resources import torch The provided code snippet includes necessary dependencies for implementing the `info_packages` function. Write a Python function `def info_packages() -> dict` to solve the following problem: Get name and version of all installed packages. Here is the function: def info_packages() -> dict: """Get name and version of all installed packages.""" packages = {} for dist in pkg_resources.working_set: package = dist.as_requirement() packages[package.key] = package.specs[0][1] return packages
Get name and version of all installed packages.
155,332
import os import platform import sys import pkg_resources import torch LEVEL_OFFSET = "\t" KEY_PADDING = 20 def nice_print(details: dict, level: int = 0) -> list: lines = [] for k in sorted(details): key = f"* {k}:" if level == 0 else f"- {k}:" if isinstance(details[k], dict): lines += [level * LEVEL_OFFSET + key] lines += nice_print(details[k], level + 1) elif isinstance(details[k], (set, list, tuple)): lines += [level * LEVEL_OFFSET + key] lines += [(level + 1) * LEVEL_OFFSET + "- " + v for v in details[k]] else: template = "{:%is} {}" % KEY_PADDING key_val = template.format(key, details[k]) lines += [(level * LEVEL_OFFSET) + key_val] return lines
null
155,333
import contextlib import glob import logging import os import tempfile from importlib.util import module_from_spec, spec_from_file_location from types import ModuleType from typing import Generator, Mapping, Optional import setuptools import setuptools.command.egg_info def _load_py_module(name: str, location: str) -> ModuleType: spec = spec_from_file_location(name, location) assert spec, f"Failed to load module {name} from {location}" py = module_from_spec(spec) assert spec.loader, f"ModuleSpec.loader is None for {name} from {location}" spec.loader.exec_module(py) return py
null
155,334
import contextlib import glob import logging import os import tempfile from importlib.util import module_from_spec, spec_from_file_location from types import ModuleType from typing import Generator, Mapping, Optional import setuptools import setuptools.command.egg_info _PACKAGE_MAPPING = { "lightning": "lightning", "pytorch": "pytorch_lightning", "app": "lightning_app", "fabric": "lightning_fabric", } _PATH_ROOT = os.path.dirname(__file__) _PATH_SRC = os.path.join(_PATH_ROOT, "src") def _named_temporary_file(directory: Optional[str] = None) -> str: # `tempfile.NamedTemporaryFile` has issues in Windows # https://github.com/deepchem/deepchem/issues/707#issuecomment-556002823 if directory is None: directory = tempfile.gettempdir() return os.path.join(directory, os.urandom(24).hex()) def _set_manifest_path(manifest_dir: str, aggregate: bool = False, mapping: Mapping = _PACKAGE_MAPPING) -> Generator: if aggregate: # aggregate all MANIFEST.in contents into a single temporary file manifest_path = _named_temporary_file(manifest_dir) lines = [] # load manifest and aggregated all manifests for pkg in mapping.values(): pkg_manifest = os.path.join(_PATH_SRC, pkg, "MANIFEST.in") if os.path.isfile(pkg_manifest): with open(pkg_manifest) as fh: lines.extend(fh.readlines()) # convert lightning_foo to lightning/foo for new, old in mapping.items(): if old == "lightning": continue # avoid `lightning` -> `lightning/lightning` lines = [ln.replace(old, f"lightning/{new}") for ln in lines] lines = sorted(set(filter(lambda ln: not ln.strip().startswith("#"), lines))) logging.debug(f"aggregated manifest consists of: {lines}") with open(manifest_path, mode="w") as fp: fp.writelines(lines) else: manifest_path = os.path.join(manifest_dir, "MANIFEST.in") assert os.path.exists(manifest_path) # avoid error: setup script specifies an absolute path manifest_path = os.path.relpath(manifest_path, _PATH_ROOT) logging.info("Set manifest path to", manifest_path) setuptools.command.egg_info.manifest_maker.template = manifest_path yield # cleanup setuptools.command.egg_info.manifest_maker.template = "MANIFEST.in" if aggregate: os.remove(manifest_path)
null
155,335
import inspect import os import sys import lai_sphinx_theme from lightning_utilities.docs import fetch_external_assets import lightning def setup(app): # this is for hiding doctest decoration, # see: http://z4r.github.io/python/2011/12/02/hides-the-prompts-and-output/ app.add_js_file("copybutton.js") app.add_css_file("main.css")
null
155,336
import inspect import os import sys import lai_sphinx_theme from lightning_utilities.docs import fetch_external_assets import lightning def _package_list_from_file(file): list_pkgs = [] with open(file) as fp: lines = fp.readlines() for ln in lines: found = [ln.index(ch) for ch in list(",=<>#") if ch in ln] pkg = ln[: min(found)] if found else ln if pkg.rstrip(): list_pkgs.append(pkg.rstrip()) return list_pkgs
null
155,337
import inspect import os import sys import lai_sphinx_theme from lightning_utilities.docs import fetch_external_assets import lightning sys.path.insert(0, os.path.abspath(_PATH_ROOT)) github_user = "Lightning-AI" github_repo = project def linkcode_resolve(domain, info): def find_source(): # try to find the file and line number, based on code from numpy: # https://github.com/numpy/numpy/blob/master/doc/source/conf.py#L286 obj = sys.modules[info["module"]] for part in info["fullname"].split("."): obj = getattr(obj, part) fname = inspect.getsourcefile(obj) # https://github.com/rtfd/readthedocs.org/issues/5735 if any(s in fname for s in ("readthedocs", "rtfd", "checkouts")): # /home/docs/checkouts/readthedocs.org/user_builds/pytorch_lightning/checkouts/ # devel/pytorch_lightning/utilities/cls_experiment.py#L26-L176 path_top = os.path.abspath(os.path.join("..", "..", "..")) fname = os.path.relpath(fname, start=path_top) else: # Local build, imitate master fname = "master/" + os.path.relpath(fname, start=os.path.abspath("..")) source, lineno = inspect.getsourcelines(obj) return fname, lineno, lineno + len(source) - 1 if domain != "py" or not info["module"]: return None try: filename = "%s#L%d-L%d" % find_source() except Exception: filename = info["module"].replace(".", "/") + ".py" # import subprocess # tag = subprocess.Popen(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE, # universal_newlines=True).communicate()[0][:-1] branch = filename.split("/")[0] # do mapping from latest tags to master branch = {"latest": "master", "stable": "master"}.get(branch, branch) filename = "/".join([branch] + filename.split("/")[1:]) return f"https://github.com/{github_user}/{github_repo}/blob/{filename}"
null
155,338
import glob import os import shutil import warnings from importlib.util import module_from_spec, spec_from_file_location from types import ModuleType import lai_sphinx_theme from lightning_utilities.docs import adjust_linked_external_docs, fetch_external_assets from lightning_utilities.docs.formatting import _transform_changelog import lightning def _load_py_module(name: str, location: str) -> ModuleType: spec = spec_from_file_location(name, location) py = module_from_spec(spec) spec.loader.exec_module(py) return py
null
155,339
import glob import os import shutil import warnings from importlib.util import module_from_spec, spec_from_file_location from types import ModuleType import lai_sphinx_theme from lightning_utilities.docs import adjust_linked_external_docs, fetch_external_assets from lightning_utilities.docs.formatting import _transform_changelog import lightning def setup(app): # this is for hiding doctest decoration, # see: http://z4r.github.io/python/2011/12/02/hides-the-prompts-and-output/ app.add_js_file("copybutton.js") app.add_css_file("main.css")
null
155,340
import glob import os import shutil import warnings from importlib.util import module_from_spec, spec_from_file_location from types import ModuleType import lai_sphinx_theme from lightning_utilities.docs import adjust_linked_external_docs, fetch_external_assets from lightning_utilities.docs.formatting import _transform_changelog import lightning The provided code snippet includes necessary dependencies for implementing the `package_list_from_file` function. Write a Python function `def package_list_from_file(file)` to solve the following problem: List up package name (not containing version and extras) from a package list file. Here is the function: def package_list_from_file(file): """List up package name (not containing version and extras) from a package list file.""" mocked_packages = [] with open(file) as fp: for ln in fp.readlines(): # Example: `tqdm>=4.41.0` => `tqdm` # `[` is for package with extras found = [ln.index(ch) for ch in list(",=<>#[") if ch in ln] pkg = ln[: min(found)] if found else ln if pkg.rstrip(): mocked_packages.append(pkg.rstrip()) return mocked_packages
List up package name (not containing version and extras) from a package list file.
155,341
import io import os import subprocess import sys from copy import deepcopy from functools import partial from subprocess import Popen from typing import Dict, List, Optional from lightning import BuildConfig, CloudCompute, LightningApp, LightningFlow from lightning.app import structures from lightning.app.components import TracerPythonScript from lightning.app.frontend import StreamlitFrontend from lightning.app.storage.path import Path from lightning.app.utilities.state import AppState def page_1__create_new_run(state): import streamlit as st st.markdown("# Create a new Run 🎈") # 1: Collect arguments from the users id = st.text_input("Name your run", value="my_first_run") github_repo = st.text_input( "Enter a Github Repo URL", value="https://github.com/Lightning-AI/lightning-quick-start.git" ) default_script_args = ( "--trainer.max_epochs=5" " --trainer.limit_train_batches=4" " --trainer.limit_val_batches=4" " --trainer.callbacks=ModelCheckpoint" " --trainer.callbacks.monitor=val_acc" ) default_requirements = "torchvision, pytorch_lightning, jsonargparse[signatures]" script_path = st.text_input("Enter your script to run", value="train_script.py") script_args = st.text_input("Enter your base script arguments", value=default_script_args) requirements = st.text_input("Enter your requirements", value=default_requirements) ml_framework = st.radio( "Select your ML Training Frameworks", options=["PyTorch Lightning", "Keras", "Tensorflow"] ) if ml_framework not in ("PyTorch Lightning"): st.write(f"{ml_framework} isn't supported yet.") return clicked = st.button("Submit") # 2: If clicked, create a new request. if clicked: new_request = { "id": id, "train": { "github_repo": github_repo, "script_path": script_path, "script_args": script_args.split(" "), "requirements": requirements.split(" "), "ml_framework": ml_framework, }, } # 3: IMPORTANT: Add a new request to the state in-place. # The flow receives the UI request and dynamically create # and run the associated work from the request information. state.requests = state.requests + [new_request] def page_2__view_run_lists(state): import streamlit as st st.markdown("# Run Lists 🎈") # 1: Iterate through all the requests in the state. for i, r in enumerate(state.requests): i = str(i) # 2: Display information such as request, logs, work state, model score. work = state._state["structures"]["ws"]["works"][f"w_{i}"] with st.expander(f"Expand to view Run {i}", expanded=False): if st.checkbox("Expand to view your configuration", key=i): st.json(r) if st.checkbox("Expand to view logs", key=i): st.code(body=work["vars"]["logs"]) if st.checkbox("Expand to view your work state", key=i): work["vars"].pop("logs") st.json(work) best_model_score = r.get("best_model_score", None) if best_model_score: if st.checkbox("Expand to view your run performance", key=i): st.json({"best_model_score": best_model_score, "best_model_path": r.get("best_model_path")}) def page_3__view_app_state(state): import streamlit as st st.markdown("# App State 🎈") st.write(state._state) class AppState: _APP_PRIVATE_KEYS: Tuple[str, ...] = ( "_use_localhost", "_host", "_session_id", "_state", "_last_state", "_url", "_port", "_request_state", "_store_state", "_send_state", "_my_affiliation", "_find_state_under_affiliation", "_plugin", "_attach_plugin", "_authorized", "is_authorized", "_debug", "_session", ) _MY_AFFILIATION: Tuple[str, ...] = () def __init__( self, host: Optional[str] = None, port: Optional[int] = None, last_state: Optional[Dict] = None, state: Optional[Dict] = None, my_affiliation: Tuple[str, ...] = None, plugin: Optional[BaseStatePlugin] = None, ) -> None: """The AppState class enables Frontend users to interact with their application state. When the state isn't defined, it would be pulled from the app REST API Server. If the state gets modified by the user, the new state would be sent to the API Server. Arguments: host: Rest API Server current host port: Rest API Server current port last_state: The state pulled on first access. state: The state modified by the user. my_affiliation: A tuple describing the affiliation this app state represents. When storing a state dict on this AppState, this affiliation will be used to reduce the scope of the given state. plugin: A plugin to handle authorization. """ self._use_localhost = "LIGHTNING_APP_STATE_URL" not in os.environ self._host = host or ("http://127.0.0.1" if self._use_localhost else None) self._port = port or (APP_SERVER_PORT if self._use_localhost else None) self._last_state = last_state self._state = state self._session_id = "1234" self._my_affiliation = my_affiliation if my_affiliation is not None else AppState._MY_AFFILIATION self._authorized = None self._attach_plugin(plugin) self._session = self._configure_session() def _url(self) -> str: if self._host is None: app_ip = "" if "LIGHTNING_CLOUD_PROJECT_ID" in os.environ and "LIGHTNING_CLOUD_APP_ID" in os.environ: client = LightningClient() app_instance = client.lightningapp_instance_service_get_lightningapp_instance( os.environ.get("LIGHTNING_CLOUD_PROJECT_ID"), os.environ.get("LIGHTNING_CLOUD_APP_ID"), ) app_ip = app_instance.status.ip_address # TODO: Don't hard code port 8080 here self._host = f"http://{app_ip}:8080" if app_ip else APP_SERVER_HOST return f"{self._host}:{self._port}" if self._use_localhost else self._host def _attach_plugin(self, plugin: Optional[BaseStatePlugin]) -> None: plugin = plugin if plugin is not None else AppStatePlugin() self._plugin = plugin def _find_state_under_affiliation(state, my_affiliation: Tuple[str, ...]) -> Dict[str, Any]: """This method is used to extract the subset of the app state associated with the given affiliation. For example, if the affiliation is ``("root", "subflow")``, then the returned state will be ``state["flows"]["subflow"]``. """ children_state = state for name in my_affiliation: if name in children_state["flows"]: children_state = children_state["flows"][name] elif name in children_state["works"]: children_state = children_state["works"][name] else: raise ValueError(f"Failed to extract the state under the affiliation '{my_affiliation}'.") return children_state def _store_state(self, state: Dict[str, Any]) -> None: # Relying on the global variable to ensure the # deep_diff is done on the entire state. global _LAST_STATE global _STATE _LAST_STATE = deepcopy(state) _STATE = state # If the affiliation is passed, the AppState was created in a LightningFlow context. # The state should be only the one of this LightningFlow and its children. self._last_state = self._find_state_under_affiliation(_LAST_STATE, self._my_affiliation) self._state = self._find_state_under_affiliation(_STATE, self._my_affiliation) def send_delta(self) -> None: app_url = f"{self._url}/api/v1/delta" deep_diff = DeepDiff(_LAST_STATE, _STATE, verbose_level=2) assert self._plugin is not None # TODO: Find how to prevent the infinite loop on refresh without storing the DeepDiff if self._plugin.should_update_app(deep_diff): data = {"delta": json.loads(deep_diff.to_json())} headers = headers_for(self._plugin.get_context()) try: # TODO: Send the delta directly to the REST API. response = self._session.post(app_url, json=data, headers=headers) except ConnectionError as ex: raise AttributeError("Failed to connect and send the app state. Is the app running?") from ex if response and response.status_code != 200: raise Exception(f"The response from the server was {response.status_code}. Your inputs were rejected.") def _request_state(self) -> None: if self._state is not None: return app_url = f"{self._url}/api/v1/state" headers = headers_for(self._plugin.get_context()) if self._plugin else {} response_json = {} # Sometimes the state URL can return an empty JSON when things are being set-up, # so we wait for it to be ready here. while response_json == {}: sleep(0.5) try: response = self._session.get(app_url, headers=headers, timeout=1) except ConnectionError as ex: raise AttributeError("Failed to connect and fetch the app state. Is the app running?") from ex self._authorized = response.status_code if self._authorized != 200: return response_json = response.json() logger.debug(f"GET STATE {response} {response_json}") self._store_state(response_json) def __getattr__(self, name: str) -> Union[Any, "AppState"]: if name in self._APP_PRIVATE_KEYS: return object.__getattr__(self, name) # The state needs to be fetched on access if it doesn't exist. self._request_state() if name in self._state.get("vars", {}): value = self._state["vars"][name] if isinstance(value, dict): return _maybe_create_drive("root." + ".".join(self._my_affiliation), value) return value if name in self._state.get("works", {}): return AppState( self._host, self._port, last_state=self._last_state["works"][name], state=self._state["works"][name] ) if name in self._state.get("flows", {}): return AppState( self._host, self._port, last_state=self._last_state["flows"][name], state=self._state["flows"][name], ) if name in self._state.get("structures", {}): return AppState( self._host, self._port, last_state=self._last_state["structures"][name], state=self._state["structures"][name], ) raise AttributeError( f"Failed to access '{name}' through `AppState`. The state provides:" f" Variables: {list(self._state['vars'].keys())}," f" Components: {list(self._state.get('flows', {}).keys()) + list(self._state.get('works', {}).keys())}", ) def __getitem__(self, key: str): return self.__getattr__(key) def __setattr__(self, name: str, value: Any) -> None: if name in self._APP_PRIVATE_KEYS: object.__setattr__(self, name, value) return # The state needs to be fetched on access if it doesn't exist. self._request_state() # TODO: Find a way to aggregate deltas to avoid making # request for each attribute change. if name in self._state["vars"]: self._state["vars"][name] = value self.send_delta() elif name in self._state["flows"]: raise AttributeError("You shouldn't set the flows directly onto the state. Use its attributes instead.") elif name in self._state["works"]: raise AttributeError("You shouldn't set the works directly onto the state. Use its attributes instead.") else: raise AttributeError( f"Failed to access '{name}' through `AppState`. The state provides:" f" Variables: {list(self._state['vars'].keys())}," f" Components: {list(self._state['flows'].keys()) + list(self._state['works'].keys())}", ) def __repr__(self) -> str: return str(self._state) def __bool__(self) -> bool: return bool(self._state) def __len__(self) -> int: # The state needs to be fetched on access if it doesn't exist. self._request_state() keys = [] for component in ["flows", "works", "structures"]: keys.extend(list(self._state.get(component, {}))) return len(keys) def items(self) -> List[Dict[str, Any]]: # The state needs to be fetched on access if it doesn't exist. self._request_state() items = [] for component in ["flows", "works"]: state = self._state.get(component, {}) last_state = self._last_state.get(component, {}) for name, state_value in state.items(): v = AppState( self._host, self._port, last_state=last_state[name], state=state_value, ) items.append((name, v)) structures = self._state.get("structures", {}) last_structures = self._last_state.get("structures", {}) if structures: for component in ["flows", "works"]: state = structures.get(component, {}) last_state = last_structures.get(component, {}) for name, state_value in state.items(): v = AppState( self._host, self._port, last_state=last_state[name], state=state_value, ) items.append((name, v)) return items def _configure_session() -> Session: return _configure_session() def render_fn(state: AppState): import streamlit as st page_names_to_funcs = { "Create a new Run": partial(page_1__create_new_run, state=state), "View your Runs": partial(page_2__view_run_lists, state=state), "View the App state": partial(page_3__view_app_state, state=state), } selected_page = st.sidebar.selectbox( "Select a page", page_names_to_funcs.keys()) page_names_to_funcs[selected_page]()
null
155,342
import json import os import tarfile import uuid import zipfile from pathlib import Path from lightning.app import LightningWork, LightningApp from lightning.app.storage import Drive import requests from lightning import LightningWork from lightning import LightningApp, LightningFlow class Flow(LightningFlow): def __init__(self): def run(self): def configure_layout(self): from lightning.app.runners import MultiProcessRuntime from lightning.app.testing import run_app_in_cloud def test_file_server(): app = LightningApp(Flow()) MultiProcessRuntime(app).dispatch()
null
155,343
import json import os import tarfile import uuid import zipfile from pathlib import Path from lightning.app import LightningWork, LightningApp from lightning.app.storage import Drive import requests from lightning import LightningWork from lightning import LightningApp, LightningFlow from lightning.app.runners import MultiProcessRuntime from lightning.app.testing import run_app_in_cloud def test_file_server_in_cloud(): # You need to provide the directory containing the app file. app_dir = "docs/source-app/examples/file_server" with run_app_in_cloud(app_dir) as (admin_page, view_page, get_logs_fn, name): """# 1. `admin_page` and `view_page` are playwright Page Objects. # Check out https://playwright.dev/python/ doc to learn more. # You can click the UI and trigger actions. # 2. By calling logs = get_logs_fn(), # you get all the logs currently on the admin page. """
null
155,344
import os from lightning.app import LightningFlow, LightningApp from lightning.app.frontend import StaticWebFrontend, StreamlitFrontend from lightning.app.utilities.state import AppState class AppState: _APP_PRIVATE_KEYS: Tuple[str, ...] = ( "_use_localhost", "_host", "_session_id", "_state", "_last_state", "_url", "_port", "_request_state", "_store_state", "_send_state", "_my_affiliation", "_find_state_under_affiliation", "_plugin", "_attach_plugin", "_authorized", "is_authorized", "_debug", "_session", ) _MY_AFFILIATION: Tuple[str, ...] = () def __init__( self, host: Optional[str] = None, port: Optional[int] = None, last_state: Optional[Dict] = None, state: Optional[Dict] = None, my_affiliation: Tuple[str, ...] = None, plugin: Optional[BaseStatePlugin] = None, ) -> None: """The AppState class enables Frontend users to interact with their application state. When the state isn't defined, it would be pulled from the app REST API Server. If the state gets modified by the user, the new state would be sent to the API Server. Arguments: host: Rest API Server current host port: Rest API Server current port last_state: The state pulled on first access. state: The state modified by the user. my_affiliation: A tuple describing the affiliation this app state represents. When storing a state dict on this AppState, this affiliation will be used to reduce the scope of the given state. plugin: A plugin to handle authorization. """ self._use_localhost = "LIGHTNING_APP_STATE_URL" not in os.environ self._host = host or ("http://127.0.0.1" if self._use_localhost else None) self._port = port or (APP_SERVER_PORT if self._use_localhost else None) self._last_state = last_state self._state = state self._session_id = "1234" self._my_affiliation = my_affiliation if my_affiliation is not None else AppState._MY_AFFILIATION self._authorized = None self._attach_plugin(plugin) self._session = self._configure_session() def _url(self) -> str: if self._host is None: app_ip = "" if "LIGHTNING_CLOUD_PROJECT_ID" in os.environ and "LIGHTNING_CLOUD_APP_ID" in os.environ: client = LightningClient() app_instance = client.lightningapp_instance_service_get_lightningapp_instance( os.environ.get("LIGHTNING_CLOUD_PROJECT_ID"), os.environ.get("LIGHTNING_CLOUD_APP_ID"), ) app_ip = app_instance.status.ip_address # TODO: Don't hard code port 8080 here self._host = f"http://{app_ip}:8080" if app_ip else APP_SERVER_HOST return f"{self._host}:{self._port}" if self._use_localhost else self._host def _attach_plugin(self, plugin: Optional[BaseStatePlugin]) -> None: plugin = plugin if plugin is not None else AppStatePlugin() self._plugin = plugin def _find_state_under_affiliation(state, my_affiliation: Tuple[str, ...]) -> Dict[str, Any]: """This method is used to extract the subset of the app state associated with the given affiliation. For example, if the affiliation is ``("root", "subflow")``, then the returned state will be ``state["flows"]["subflow"]``. """ children_state = state for name in my_affiliation: if name in children_state["flows"]: children_state = children_state["flows"][name] elif name in children_state["works"]: children_state = children_state["works"][name] else: raise ValueError(f"Failed to extract the state under the affiliation '{my_affiliation}'.") return children_state def _store_state(self, state: Dict[str, Any]) -> None: # Relying on the global variable to ensure the # deep_diff is done on the entire state. global _LAST_STATE global _STATE _LAST_STATE = deepcopy(state) _STATE = state # If the affiliation is passed, the AppState was created in a LightningFlow context. # The state should be only the one of this LightningFlow and its children. self._last_state = self._find_state_under_affiliation(_LAST_STATE, self._my_affiliation) self._state = self._find_state_under_affiliation(_STATE, self._my_affiliation) def send_delta(self) -> None: app_url = f"{self._url}/api/v1/delta" deep_diff = DeepDiff(_LAST_STATE, _STATE, verbose_level=2) assert self._plugin is not None # TODO: Find how to prevent the infinite loop on refresh without storing the DeepDiff if self._plugin.should_update_app(deep_diff): data = {"delta": json.loads(deep_diff.to_json())} headers = headers_for(self._plugin.get_context()) try: # TODO: Send the delta directly to the REST API. response = self._session.post(app_url, json=data, headers=headers) except ConnectionError as ex: raise AttributeError("Failed to connect and send the app state. Is the app running?") from ex if response and response.status_code != 200: raise Exception(f"The response from the server was {response.status_code}. Your inputs were rejected.") def _request_state(self) -> None: if self._state is not None: return app_url = f"{self._url}/api/v1/state" headers = headers_for(self._plugin.get_context()) if self._plugin else {} response_json = {} # Sometimes the state URL can return an empty JSON when things are being set-up, # so we wait for it to be ready here. while response_json == {}: sleep(0.5) try: response = self._session.get(app_url, headers=headers, timeout=1) except ConnectionError as ex: raise AttributeError("Failed to connect and fetch the app state. Is the app running?") from ex self._authorized = response.status_code if self._authorized != 200: return response_json = response.json() logger.debug(f"GET STATE {response} {response_json}") self._store_state(response_json) def __getattr__(self, name: str) -> Union[Any, "AppState"]: if name in self._APP_PRIVATE_KEYS: return object.__getattr__(self, name) # The state needs to be fetched on access if it doesn't exist. self._request_state() if name in self._state.get("vars", {}): value = self._state["vars"][name] if isinstance(value, dict): return _maybe_create_drive("root." + ".".join(self._my_affiliation), value) return value if name in self._state.get("works", {}): return AppState( self._host, self._port, last_state=self._last_state["works"][name], state=self._state["works"][name] ) if name in self._state.get("flows", {}): return AppState( self._host, self._port, last_state=self._last_state["flows"][name], state=self._state["flows"][name], ) if name in self._state.get("structures", {}): return AppState( self._host, self._port, last_state=self._last_state["structures"][name], state=self._state["structures"][name], ) raise AttributeError( f"Failed to access '{name}' through `AppState`. The state provides:" f" Variables: {list(self._state['vars'].keys())}," f" Components: {list(self._state.get('flows', {}).keys()) + list(self._state.get('works', {}).keys())}", ) def __getitem__(self, key: str): return self.__getattr__(key) def __setattr__(self, name: str, value: Any) -> None: if name in self._APP_PRIVATE_KEYS: object.__setattr__(self, name, value) return # The state needs to be fetched on access if it doesn't exist. self._request_state() # TODO: Find a way to aggregate deltas to avoid making # request for each attribute change. if name in self._state["vars"]: self._state["vars"][name] = value self.send_delta() elif name in self._state["flows"]: raise AttributeError("You shouldn't set the flows directly onto the state. Use its attributes instead.") elif name in self._state["works"]: raise AttributeError("You shouldn't set the works directly onto the state. Use its attributes instead.") else: raise AttributeError( f"Failed to access '{name}' through `AppState`. The state provides:" f" Variables: {list(self._state['vars'].keys())}," f" Components: {list(self._state['flows'].keys()) + list(self._state['works'].keys())}", ) def __repr__(self) -> str: return str(self._state) def __bool__(self) -> bool: return bool(self._state) def __len__(self) -> int: # The state needs to be fetched on access if it doesn't exist. self._request_state() keys = [] for component in ["flows", "works", "structures"]: keys.extend(list(self._state.get(component, {}))) return len(keys) def items(self) -> List[Dict[str, Any]]: # The state needs to be fetched on access if it doesn't exist. self._request_state() items = [] for component in ["flows", "works"]: state = self._state.get(component, {}) last_state = self._last_state.get(component, {}) for name, state_value in state.items(): v = AppState( self._host, self._port, last_state=last_state[name], state=state_value, ) items.append((name, v)) structures = self._state.get("structures", {}) last_structures = self._last_state.get("structures", {}) if structures: for component in ["flows", "works"]: state = structures.get(component, {}) last_state = last_structures.get(component, {}) for name, state_value in state.items(): v = AppState( self._host, self._port, last_state=last_state[name], state=state_value, ) items.append((name, v)) return items def _configure_session() -> Session: return _configure_session() def render_fn(state: AppState): import streamlit as st from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=None, key="refresh") state.should_print = st.select_slider( "Should the Application print 'Hello World !' to the terminal:", [False, True], )
null
155,345
from lightning.app import LightningWork, LightningApp, CloudCompute from lightning.app.components import MultiNode import torch from torch.nn.parallel.distributed import DistributedDataParallel def distributed_train(local_rank: int, main_address: str, main_port: int, num_nodes: int, node_rank: int, nprocs: int): # 1. SET UP DISTRIBUTED ENVIRONMENT global_rank = local_rank + node_rank * nprocs world_size = num_nodes * nprocs if torch.distributed.is_available() and not torch.distributed.is_initialized(): torch.distributed.init_process_group( "nccl" if torch.cuda.is_available() else "gloo", rank=global_rank, world_size=world_size, init_method=f"tcp://{main_address}:{main_port}", ) # 2. PREPARE DISTRIBUTED MODEL model = torch.nn.Linear(32, 2) device = torch.device(f"cuda:{local_rank}") if torch.cuda.is_available() else torch.device("cpu") model = DistributedDataParallel(model, device_ids=[local_rank] if torch.cuda.is_available() else None).to(device) # 3. SETUP LOSS AND OPTIMIZER criterion = torch.nn.MSELoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # 4.TRAIN THE MODEL FOR 50 STEPS for step in range(50): model.zero_grad() x = torch.randn(64, 32).to(device) output = model(x) loss = criterion(output, torch.ones_like(output)) print(f"global_rank: {global_rank} step: {step} loss: {loss}") loss.backward() optimizer.step() # 5. VERIFY ALL COPIES OF THE MODEL HAVE THE SAME WEIGTHS AT END OF TRAINING weight = model.module.weight.clone() torch.distributed.all_reduce(weight) assert torch.equal(model.module.weight, weight / world_size) print("Multi Node Distributed Training Done!")
null
155,346
import glob import inspect import os import shutil import sys import lai_sphinx_theme from lightning_utilities.docs import fetch_external_assets import lightning def setup(app): # this is for hiding doctest decoration, # see: http://z4r.github.io/python/2011/12/02/hides-the-prompts-and-output/ app.add_js_file("copybutton.js") app.add_css_file("main.css")
null
155,347
import glob import inspect import os import shutil import sys import lai_sphinx_theme from lightning_utilities.docs import fetch_external_assets import lightning def _package_list_from_file(file): list_pkgs = [] with open(file) as fp: lines = fp.readlines() for ln in lines: found = [ln.index(ch) for ch in list(",=<>#") if ch in ln] pkg = ln[: min(found)] if found else ln if pkg.rstrip(): list_pkgs.append(pkg.rstrip()) return list_pkgs
null
155,348
import glob import inspect import os import shutil import sys import lai_sphinx_theme from lightning_utilities.docs import fetch_external_assets import lightning sys.path.insert(0, os.path.abspath(_PATH_ROOT)) github_user = "Lightning-AI" github_repo = project if not os.path.isdir(path_nbs): os.mkdir(path_nbs) if not os.path.isdir(path_examples): os.mkdir(path_examples) def linkcode_resolve(domain, info): def find_source(): # try to find the file and line number, based on code from numpy: # https://github.com/numpy/numpy/blob/master/doc/source/conf.py#L286 obj = sys.modules[info["module"]] for part in info["fullname"].split("."): obj = getattr(obj, part) fname = inspect.getsourcefile(obj) # https://github.com/rtfd/readthedocs.org/issues/5735 if any(s in fname for s in ("readthedocs", "rtfd", "checkouts")): # /home/docs/checkouts/readthedocs.org/user_builds/pytorch_lightning/checkouts/ # devel/pytorch_lightning/utilities/cls_experiment.py#L26-L176 path_top = os.path.abspath(os.path.join("..", "..", "..")) fname = os.path.relpath(fname, start=path_top) else: # Local build, imitate master fname = "master/" + os.path.relpath(fname, start=os.path.abspath("..")) source, lineno = inspect.getsourcelines(obj) return fname, lineno, lineno + len(source) - 1 if domain != "py" or not info["module"]: return None try: filename = "%s#L%d-L%d" % find_source() except Exception: filename = info["module"].replace(".", "/") + ".py" # import subprocess # tag = subprocess.Popen(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE, # universal_newlines=True).communicate()[0][:-1] branch = filename.split("/")[0] # do mapping from latest tags to master branch = {"latest": "master", "stable": "master"}.get(branch, branch) filename = "/".join([branch] + filename.split("/")[1:]) return f"https://github.com/{github_user}/{github_repo}/blob/{filename}"
null
155,349
import glob import os.path from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from types import ModuleType from typing import Any, Dict from pkg_resources import parse_requirements from setuptools import find_packages _PACKAGE_ROOT = os.path.join(_SOURCE_ROOT, "pytorch_lightning") _PATH_REQUIREMENTS = os.path.join("requirements", "pytorch") _FREEZE_REQUIREMENTS = os.environ.get("FREEZE_REQUIREMENTS", "0").lower() in ("1", "true") def _load_py_module(name: str, location: str) -> ModuleType: spec = spec_from_file_location(name, location) assert spec, f"Failed to load module {name} from {location}" py = module_from_spec(spec) assert spec.loader, f"ModuleSpec.loader is None for {name} from {location}" spec.loader.exec_module(py) return py def _load_assistant() -> ModuleType: location = os.path.join(_PROJECT_ROOT, ".actions", "assistant.py") return _load_py_module("assistant", location) def _prepare_extras() -> Dict[str, Any]: assistant = _load_assistant() # https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras # Define package extras. These are only installed if you specify them. # From remote, use like `pip install "pytorch-lightning[dev, docs]"` # From local copy of repo, use like `PACKAGE_NAME=pytorch pip install ".[dev, docs]"` common_args = {"path_dir": _PATH_REQUIREMENTS, "unfreeze": "none" if _FREEZE_REQUIREMENTS else "all"} req_files = [Path(p) for p in glob.glob(os.path.join(_PATH_REQUIREMENTS, "*.txt"))] extras = { p.stem: assistant.load_requirements(file_name=p.name, **common_args) for p in req_files if p.name not in ("docs.txt", "base.txt") } for req in parse_requirements(extras["strategies"]): extras[req.key] = [str(req)] extras["all"] = extras["extra"] + extras["strategies"] + extras["examples"] extras["dev"] = extras["all"] + extras["test"] # + extras['docs'] return extras def _setup_args() -> Dict[str, Any]: assistant = _load_assistant() about = _load_py_module("about", os.path.join(_PACKAGE_ROOT, "__about__.py")) version = _load_py_module("version", os.path.join(_PACKAGE_ROOT, "__version__.py")) long_description = assistant.load_readme_description( _PACKAGE_ROOT, homepage=about.__homepage__, version=version.version ) return { "name": "pytorch-lightning", "version": version.version, "description": about.__docs__, "author": about.__author__, "author_email": about.__author_email__, "url": about.__homepage__, "download_url": "https://github.com/Lightning-AI/lightning", "license": about.__license__, "packages": find_packages( where="src", include=[ "pytorch_lightning", "pytorch_lightning.*", "lightning_fabric", "lightning_fabric.*", ], ), "package_dir": {"": "src"}, "include_package_data": True, "long_description": long_description, "long_description_content_type": "text/markdown", "zip_safe": False, "keywords": ["deep learning", "pytorch", "AI"], "python_requires": ">=3.8", "setup_requires": ["wheel"], # TODO: aggregate pytorch and lite requirements as we include its source code directly in this package. # this is not a problem yet because lite's base requirements are all included in pytorch's base requirements "install_requires": assistant.load_requirements( _PATH_REQUIREMENTS, unfreeze="none" if _FREEZE_REQUIREMENTS else "all" ), "extras_require": _prepare_extras(), "project_urls": { "Bug Tracker": "https://github.com/Lightning-AI/lightning/issues", "Documentation": "https://pytorch-lightning.rtfd.io/en/latest/", "Source Code": "https://github.com/Lightning-AI/lightning", }, "classifiers": [ "Environment :: Console", "Natural Language :: English", "Development Status :: 5 - Production/Stable", # Indicate who your project is intended for "Intended Audience :: Developers", "Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: Scientific/Engineering :: Image Recognition", "Topic :: Scientific/Engineering :: Information Analysis", # Pick your license as you wish "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", # Specify the Python versions you support here. "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", ], }
null
155,350
import glob import os from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from types import ModuleType from typing import Any, Dict from setuptools import find_packages _SOURCE_ROOT = os.path.join(_PROJECT_ROOT, "src") _PACKAGE_ROOT = os.path.join(_SOURCE_ROOT, "lightning_app") _PATH_REQUIREMENTS = os.path.join("requirements", "app") _FREEZE_REQUIREMENTS = os.environ.get("FREEZE_REQUIREMENTS", "0").lower() in ("1", "true") def _load_py_module(name: str, location: str) -> ModuleType: def _load_assistant() -> ModuleType: def _prepare_extras() -> Dict[str, Any]: def _setup_args() -> Dict[str, Any]: assistant = _load_assistant() about = _load_py_module("about", os.path.join(_PACKAGE_ROOT, "__about__.py")) version = _load_py_module("version", os.path.join(_PACKAGE_ROOT, "__version__.py")) long_description = assistant.load_readme_description( _PACKAGE_ROOT, homepage=about.__homepage__, version=version.version ) # TODO: remove this once lightning-ui package is ready as a dependency ui_ver_file = os.path.join(_SOURCE_ROOT, "app-ui-version.info") if os.path.isfile(ui_ver_file): with open(ui_ver_file, encoding="utf-8") as fo: ui_version = fo.readlines()[0].strip() download_fe_version = {"version": ui_version} else: print(f"Missing file with FE version: {ui_ver_file}") download_fe_version = {} assistant._download_frontend(_PACKAGE_ROOT, **download_fe_version) return { "name": "lightning-app", "version": version.version, "description": about.__docs__, "author": about.__author__, "author_email": about.__author_email__, "url": about.__homepage__, "download_url": "https://github.com/Lightning-AI/lightning", "license": about.__license__, "packages": find_packages(where="src", include=["lightning_app", "lightning_app.*"]), "package_dir": {"": "src"}, "long_description": long_description, "long_description_content_type": "text/markdown", "include_package_data": True, "zip_safe": False, "keywords": ["deep learning", "pytorch", "AI"], "python_requires": ">=3.8", "entry_points": { "console_scripts": [ "lightning_app = lightning_app.cli.lightning_cli:main", ], }, "setup_requires": [], "install_requires": assistant.load_requirements( _PATH_REQUIREMENTS, file_name="app.txt", unfreeze="none" if _FREEZE_REQUIREMENTS else "major" ), "extras_require": _prepare_extras(), "project_urls": { "Bug Tracker": "https://github.com/Lightning-AI/lightning/issues", "Documentation": "https://lightning.ai/lightning-docs", "Source Code": "https://github.com/Lightning-AI/lightning", }, "classifiers": [ "Environment :: Console", "Natural Language :: English", # How mature is this project? Common values are # 3 - Alpha, 4 - Beta, 5 - Production/Stable "Development Status :: 4 - Beta", # Indicate who your project is intended for "Intended Audience :: Developers", "Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: Scientific/Engineering :: Information Analysis", # Pick your license as you wish # 'License :: OSI Approved :: BSD License', "Operating System :: OS Independent", # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", ], }
null
155,351
import glob import os.path from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from types import ModuleType from typing import Any, Dict from setuptools import find_packages _PROJECT_ROOT = "." _SOURCE_ROOT = os.path.join(_PROJECT_ROOT, "src") _PACKAGE_ROOT = os.path.join(_SOURCE_ROOT, "lightning") _PATH_REQUIREMENTS = os.path.join(_PROJECT_ROOT, "requirements") _FREEZE_REQUIREMENTS = os.environ.get("FREEZE_REQUIREMENTS", "0").lower() in ("1", "true") def _load_py_module(name: str, location: str) -> ModuleType: spec = spec_from_file_location(name, location) assert spec, f"Failed to load module {name} from {location}" py = module_from_spec(spec) assert spec.loader, f"ModuleSpec.loader is None for {name} from {location}" spec.loader.exec_module(py) return py _ASSISTANT = _load_py_module(name="assistant", location=os.path.join(_PROJECT_ROOT, ".actions", "assistant.py")) def _prepare_extras() -> Dict[str, Any]: # https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras # Define package extras. These are only installed if you specify them. # From remote, use like `pip install "lightning[dev, docs]"` # From local copy of repo, use like `pip install ".[dev, docs]"` req_files = [Path(p) for p in glob.glob(os.path.join(_PATH_REQUIREMENTS, "*", "*.txt"))] common_args = {"unfreeze": "none" if _FREEZE_REQUIREMENTS else "major"} # per-project extras extras = { f"{p.parent.name}-{p.stem}": _ASSISTANT.load_requirements(file_name=p.name, path_dir=p.parent, **common_args) for p in req_files if p.name not in ("docs.txt", "base.txt") and not p.parent.name.startswith("_") } # project specific extras groups extras["fabric-all"] = extras["fabric-strategies"] + extras["fabric-examples"] extras["fabric-dev"] = extras["fabric-all"] + extras["fabric-test"] extras["pytorch-all"] = extras["pytorch-extra"] + extras["pytorch-strategies"] + extras["pytorch-examples"] extras["pytorch-dev"] = extras["pytorch-all"] + extras["pytorch-test"] extras["app-extra"] = extras["app-app"] + extras["app-cloud"] + extras["app-ui"] + extras["app-components"] extras["app-all"] = extras["app-extra"] extras["app-dev"] = extras["app-all"] + extras["app-test"] extras["store-store"] = extras["app-app"] # todo: consider cutting/leaning this dependency # merge per-project extras of the same category, e.g. `app-test` + `fabric-test` for extra in list(extras): name = "-".join(extra.split("-")[1:]) extras[name] = extras.get(name, []) + extras[extra] # drop quasi base the req. file has the same name sub-package for k in list(extras.keys()): kk = k.split("-") if not (len(kk) == 2 and kk[0] == kk[1]): continue extras[kk[0]] = list(extras[k]) del extras[k] extras = {name: sorted(set(reqs)) for name, reqs in extras.items()} print("The extras are: ", extras) return extras def _setup_args() -> Dict[str, Any]: about = _load_py_module("about", os.path.join(_PACKAGE_ROOT, "__about__.py")) version = _load_py_module("version", os.path.join(_PACKAGE_ROOT, "__version__.py")) long_description = _ASSISTANT.load_readme_description( _PROJECT_ROOT, homepage=about.__homepage__, version=version.version ) # TODO: remove this once lightning-ui package is ready as a dependency ui_ver_file = os.path.join(_SOURCE_ROOT, "app-ui-version.info") if os.path.isfile(ui_ver_file): with open(ui_ver_file, encoding="utf-8") as fo: ui_version = fo.readlines()[0].strip() download_fe_version = {"version": ui_version} else: print(f"Missing file with FE version: {ui_ver_file}") download_fe_version = {} _ASSISTANT._download_frontend(os.path.join(_PACKAGE_ROOT, "app"), **download_fe_version) # TODO: consider invaliding some additional arguments from packages, for example if include data or safe to zip install_requires = _ASSISTANT.load_requirements( _PATH_REQUIREMENTS, unfreeze="none" if _FREEZE_REQUIREMENTS else "major" ) # toto: remove when we realize that this is making confusion as cross pkg import is not fully compatible install_requires += ["pytorch-lightning"] return { "name": "lightning", "version": version.version, "description": about.__docs__, "author": about.__author__, "author_email": about.__author_email__, "url": about.__homepage__, "download_url": "https://github.com/Lightning-AI/lightning", "license": about.__license__, "packages": find_packages(where="src", include=["lightning", "lightning.*"]), "package_dir": {"": "src"}, "long_description": long_description, "long_description_content_type": "text/markdown", "include_package_data": True, "zip_safe": False, "keywords": ["deep learning", "pytorch", "AI"], # todo: aggregate tags from all packages "python_requires": ">=3.8", # todo: take the lowes based on all packages "entry_points": { "console_scripts": [ "fabric = lightning.fabric.cli:_main", "lightning = lightning.fabric.cli:_legacy_main", "lightning_app = lightning:_cli_entry_point", ], }, "setup_requires": [], "install_requires": install_requires, "extras_require": _prepare_extras(), "project_urls": { "Bug Tracker": "https://github.com/Lightning-AI/lightning/issues", "Documentation": "https://lightning.ai/lightning-docs", "Source Code": "https://github.com/Lightning-AI/lightning", }, "classifiers": [ "Environment :: Console", "Natural Language :: English", # How mature is this project? Common values are # 3 - Alpha, 4 - Beta, 5 - Production/Stable "Development Status :: 4 - Beta", # Indicate who your project is intended for "Intended Audience :: Developers", "Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: Scientific/Engineering :: Information Analysis", # Pick your license as you wish "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", # Specify the Python versions you support here. "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", ], # todo: consider aggregation/union of tags from particular packages }
null
155,352
import itertools from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Sized, Union, cast import torch from torch import Tensor from torch.nn.parallel.distributed import DistributedDataParallel from torch.utils.data import DistributedSampler, Sampler from typing_extensions import Self, override from lightning.fabric.utilities.distributed import _DatasetSamplerWrapper from lightning.pytorch.utilities.rank_zero import rank_zero_debug, rank_zero_info from lightning.pytorch.utilities.types import _SizedIterable def _find_tensors( obj: Union[Tensor, list, tuple, dict, Any], ) -> Union[List[Tensor], itertools.chain]: # pragma: no-cover """Recursively find all tensors contained in the specified object.""" if isinstance(obj, Tensor): return [obj] if isinstance(obj, (list, tuple)): return itertools.chain(*map(_find_tensors, obj)) if isinstance(obj, dict): return itertools.chain(*map(_find_tensors, obj.values())) return [] def prepare_for_backward(model: DistributedDataParallel, output: Any) -> None: # `prepare_for_backward` is `DistributedDataParallel` specific. if torch.is_grad_enabled() and model.require_backward_grad_sync: model.require_forward_param_sync = True # We'll return the output object verbatim since it is a freeform # object. We need to find any tensors in this object, though, # because we need to figure out which parameters were used during # this forward pass, to ensure we short circuit reduction for any # unused parameters. Only if `find_unused_parameters` is set. args = list(_find_tensors(output)) if model.find_unused_parameters and not model.static_graph else [] reducer = cast(torch._C._distributed_c10d.Reducer, model.reducer) reducer._rebuild_buckets() # avoids "INTERNAL ASSERT FAILED" with `find_unused_parameters=False` reducer.prepare_for_backward(args) else: model.require_forward_param_sync = False
null
155,353
import itertools from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Sized, Union, cast import torch from torch import Tensor from torch.nn.parallel.distributed import DistributedDataParallel from torch.utils.data import DistributedSampler, Sampler from typing_extensions import Self, override from lightning.fabric.utilities.distributed import _DatasetSamplerWrapper from lightning.pytorch.utilities.rank_zero import rank_zero_debug, rank_zero_info from lightning.pytorch.utilities.types import _SizedIterable The provided code snippet includes necessary dependencies for implementing the `_register_ddp_comm_hook` function. Write a Python function `def _register_ddp_comm_hook( model: DistributedDataParallel, ddp_comm_state: Optional[object] = None, ddp_comm_hook: Optional[Callable] = None, ddp_comm_wrapper: Optional[Callable] = None, ) -> None` to solve the following problem: Function to register communication hook for DDP model https://pytorch.org/docs/master/ddp_comm_hooks.html. Args: model: DDP model ddp_comm_state: state is passed to the hook and can be used to maintain and update any state information that users would like to maintain as part of the training process. Examples: error feedback in gradient compression, peers to communicate with next in GossipGrad etc. ddp_comm_hook: hook(state: object, bucket: dist._GradBucket) -> torch.futures.Future This callable function is called once the bucket is ready. The hook can perform whatever processing is needed and return a Future indicating completion of any async work (ex: allreduce). If the hook doesn't perform any communication, it can also just return a completed Future. The Future should hold the new value of grad bucket's tensors. Once a bucket is ready, c10d reducer would call this hook and use the tensors returned by the Future and copy grads to individual parameters. ddp_comm_wrapper: communication hook wrapper to support a communication hook such as FP16 compression as wrapper, which could be combined with ddp_comm_hook Examples:: from torch.distributed.algorithms.ddp_comm_hooks import ( default_hooks as default, powerSGD_hook as powerSGD, post_localSGD_hook as post_localSGD, ) # fp16_compress_hook for compress gradients ddp_model = ... _register_ddp_comm_hook( model=ddp_model, ddp_comm_hook=default.fp16_compress_hook, ) # powerSGD_hook ddp_model = ... _register_ddp_comm_hook( model=ddp_model, ddp_comm_state=powerSGD.PowerSGDState( process_group=None, matrix_approximation_rank=1, start_powerSGD_iter=5000, ), ddp_comm_hook=powerSGD.powerSGD_hook, ) # post_localSGD_hook subgroup, _ = torch.distributed.new_subgroups() ddp_model = ... _register_ddp_comm_hook( model=ddp_model, state=post_localSGD.PostLocalSGDState( process_group=None, subgroup=subgroup, start_localSGD_iter=1_000, ), ddp_comm_hook=post_localSGD.post_localSGD_hook, ) # fp16_compress_wrapper combined with other communication hook ddp_model = ... _register_ddp_comm_hook( model=ddp_model, ddp_comm_state=powerSGD.PowerSGDState( process_group=None, matrix_approximation_rank=1, start_powerSGD_iter=5000, ), ddp_comm_hook=powerSGD.powerSGD_hook, ddp_comm_wrapper=default.fp16_compress_wrapper, ) Here is the function: def _register_ddp_comm_hook( model: DistributedDataParallel, ddp_comm_state: Optional[object] = None, ddp_comm_hook: Optional[Callable] = None, ddp_comm_wrapper: Optional[Callable] = None, ) -> None: """Function to register communication hook for DDP model https://pytorch.org/docs/master/ddp_comm_hooks.html. Args: model: DDP model ddp_comm_state: state is passed to the hook and can be used to maintain and update any state information that users would like to maintain as part of the training process. Examples: error feedback in gradient compression, peers to communicate with next in GossipGrad etc. ddp_comm_hook: hook(state: object, bucket: dist._GradBucket) -> torch.futures.Future This callable function is called once the bucket is ready. The hook can perform whatever processing is needed and return a Future indicating completion of any async work (ex: allreduce). If the hook doesn't perform any communication, it can also just return a completed Future. The Future should hold the new value of grad bucket's tensors. Once a bucket is ready, c10d reducer would call this hook and use the tensors returned by the Future and copy grads to individual parameters. ddp_comm_wrapper: communication hook wrapper to support a communication hook such as FP16 compression as wrapper, which could be combined with ddp_comm_hook Examples:: from torch.distributed.algorithms.ddp_comm_hooks import ( default_hooks as default, powerSGD_hook as powerSGD, post_localSGD_hook as post_localSGD, ) # fp16_compress_hook for compress gradients ddp_model = ... _register_ddp_comm_hook( model=ddp_model, ddp_comm_hook=default.fp16_compress_hook, ) # powerSGD_hook ddp_model = ... _register_ddp_comm_hook( model=ddp_model, ddp_comm_state=powerSGD.PowerSGDState( process_group=None, matrix_approximation_rank=1, start_powerSGD_iter=5000, ), ddp_comm_hook=powerSGD.powerSGD_hook, ) # post_localSGD_hook subgroup, _ = torch.distributed.new_subgroups() ddp_model = ... _register_ddp_comm_hook( model=ddp_model, state=post_localSGD.PostLocalSGDState( process_group=None, subgroup=subgroup, start_localSGD_iter=1_000, ), ddp_comm_hook=post_localSGD.post_localSGD_hook, ) # fp16_compress_wrapper combined with other communication hook ddp_model = ... _register_ddp_comm_hook( model=ddp_model, ddp_comm_state=powerSGD.PowerSGDState( process_group=None, matrix_approximation_rank=1, start_powerSGD_iter=5000, ), ddp_comm_hook=powerSGD.powerSGD_hook, ddp_comm_wrapper=default.fp16_compress_wrapper, ) """ if ddp_comm_hook is None: return # inform mypy that ddp_comm_hook is callable ddp_comm_hook: Callable = ddp_comm_hook if ddp_comm_wrapper is not None: rank_zero_info( f"DDP comm wrapper is provided, apply {ddp_comm_wrapper.__qualname__}({ddp_comm_hook.__qualname__})." ) ddp_comm_hook = ddp_comm_wrapper(ddp_comm_hook) rank_zero_debug(f"Registering DDP comm hook: {ddp_comm_hook.__qualname__}.") model.register_comm_hook(state=ddp_comm_state, hook=ddp_comm_hook)
Function to register communication hook for DDP model https://pytorch.org/docs/master/ddp_comm_hooks.html. Args: model: DDP model ddp_comm_state: state is passed to the hook and can be used to maintain and update any state information that users would like to maintain as part of the training process. Examples: error feedback in gradient compression, peers to communicate with next in GossipGrad etc. ddp_comm_hook: hook(state: object, bucket: dist._GradBucket) -> torch.futures.Future This callable function is called once the bucket is ready. The hook can perform whatever processing is needed and return a Future indicating completion of any async work (ex: allreduce). If the hook doesn't perform any communication, it can also just return a completed Future. The Future should hold the new value of grad bucket's tensors. Once a bucket is ready, c10d reducer would call this hook and use the tensors returned by the Future and copy grads to individual parameters. ddp_comm_wrapper: communication hook wrapper to support a communication hook such as FP16 compression as wrapper, which could be combined with ddp_comm_hook Examples:: from torch.distributed.algorithms.ddp_comm_hooks import ( default_hooks as default, powerSGD_hook as powerSGD, post_localSGD_hook as post_localSGD, ) # fp16_compress_hook for compress gradients ddp_model = ... _register_ddp_comm_hook( model=ddp_model, ddp_comm_hook=default.fp16_compress_hook, ) # powerSGD_hook ddp_model = ... _register_ddp_comm_hook( model=ddp_model, ddp_comm_state=powerSGD.PowerSGDState( process_group=None, matrix_approximation_rank=1, start_powerSGD_iter=5000, ), ddp_comm_hook=powerSGD.powerSGD_hook, ) # post_localSGD_hook subgroup, _ = torch.distributed.new_subgroups() ddp_model = ... _register_ddp_comm_hook( model=ddp_model, state=post_localSGD.PostLocalSGDState( process_group=None, subgroup=subgroup, start_localSGD_iter=1_000, ), ddp_comm_hook=post_localSGD.post_localSGD_hook, ) # fp16_compress_wrapper combined with other communication hook ddp_model = ... _register_ddp_comm_hook( model=ddp_model, ddp_comm_state=powerSGD.PowerSGDState( process_group=None, matrix_approximation_rank=1, start_powerSGD_iter=5000, ), ddp_comm_hook=powerSGD.powerSGD_hook, ddp_comm_wrapper=default.fp16_compress_wrapper, )
155,354
import itertools from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Sized, Union, cast import torch from torch import Tensor from torch.nn.parallel.distributed import DistributedDataParallel from torch.utils.data import DistributedSampler, Sampler from typing_extensions import Self, override from lightning.fabric.utilities.distributed import _DatasetSamplerWrapper from lightning.pytorch.utilities.rank_zero import rank_zero_debug, rank_zero_info from lightning.pytorch.utilities.types import _SizedIterable The provided code snippet includes necessary dependencies for implementing the `_sync_module_states` function. Write a Python function `def _sync_module_states(module: torch.nn.Module) -> None` to solve the following problem: Taken from https://github.com/pytorch/pytorch/blob/v2.0.0/torch/nn/parallel/distributed.py#L675-L682. Here is the function: def _sync_module_states(module: torch.nn.Module) -> None: """Taken from https://github.com/pytorch/pytorch/blob/v2.0.0/torch/nn/parallel/distributed.py#L675-L682.""" parameters_to_ignore = ( set(module._ddp_params_and_buffers_to_ignore) if hasattr(module, "_ddp_params_and_buffers_to_ignore") else set() ) from torch.distributed.distributed_c10d import _get_default_group from torch.distributed.utils import _sync_module_states as torch_sync_module_states torch_sync_module_states( module, _get_default_group(), 250 * 1024 * 1024, src=0, params_and_buffers_to_ignore=parameters_to_ignore, )
Taken from https://github.com/pytorch/pytorch/blob/v2.0.0/torch/nn/parallel/distributed.py#L675-L682.
155,355
import inspect import os import sys from functools import partial, update_wrapper from types import MethodType from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Type, TypeVar, Union import torch import yaml from lightning_utilities.core.imports import RequirementCache from lightning_utilities.core.rank_zero import _warn from torch.optim import Optimizer from typing_extensions import override import lightning.pytorch as pl from lightning.fabric.utilities.cloud_io import get_filesystem from lightning.fabric.utilities.types import _TORCH_LRSCHEDULER from lightning.pytorch import Callback, LightningDataModule, LightningModule, Trainer, seed_everything from lightning.pytorch.core.mixins.hparams_mixin import _given_hyperparameters_context from lightning.pytorch.utilities.exceptions import MisconfigurationException from lightning.pytorch.utilities.model_helpers import is_overridden from lightning.pytorch.utilities.rank_zero import rank_zero_warn def _global_add_class_path( class_type: Type, init_args: Optional[Union[Namespace, Dict[str, Any]]] = None ) -> Dict[str, Any]: if isinstance(init_args, Namespace): init_args = init_args.as_dict() return {"class_path": _class_path_from_class(class_type), "init_args": init_args or {}} def _add_class_path_generator(class_type: Type) -> Callable[[Namespace], Dict[str, Any]]: def add_class_path(init_args: Namespace) -> Dict[str, Any]: return _global_add_class_path(class_type, init_args) return add_class_path
null
155,356
import inspect import os import sys from functools import partial, update_wrapper from types import MethodType from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Type, TypeVar, Union import torch import yaml from lightning_utilities.core.imports import RequirementCache from lightning_utilities.core.rank_zero import _warn from torch.optim import Optimizer from typing_extensions import override import lightning.pytorch as pl from lightning.fabric.utilities.cloud_io import get_filesystem from lightning.fabric.utilities.types import _TORCH_LRSCHEDULER from lightning.pytorch import Callback, LightningDataModule, LightningModule, Trainer, seed_everything from lightning.pytorch.core.mixins.hparams_mixin import _given_hyperparameters_context from lightning.pytorch.utilities.exceptions import MisconfigurationException from lightning.pytorch.utilities.model_helpers import is_overridden from lightning.pytorch.utilities.rank_zero import rank_zero_warn The provided code snippet includes necessary dependencies for implementing the `instantiate_class` function. Write a Python function `def instantiate_class(args: Union[Any, Tuple[Any, ...]], init: Dict[str, Any]) -> Any` to solve the following problem: Instantiates a class with the given args and init. Args: args: Positional arguments required for instantiation. init: Dict of the form {"class_path":...,"init_args":...}. Returns: The instantiated class object. Here is the function: def instantiate_class(args: Union[Any, Tuple[Any, ...]], init: Dict[str, Any]) -> Any: """Instantiates a class with the given args and init. Args: args: Positional arguments required for instantiation. init: Dict of the form {"class_path":...,"init_args":...}. Returns: The instantiated class object. """ kwargs = init.get("init_args", {}) if not isinstance(args, tuple): args = (args,) class_module, class_name = init["class_path"].rsplit(".", 1) module = __import__(class_module, fromlist=[class_name]) args_class = getattr(module, class_name) return args_class(*args, **kwargs)
Instantiates a class with the given args and init. Args: args: Positional arguments required for instantiation. init: Dict of the form {"class_path":...,"init_args":...}. Returns: The instantiated class object.
155,357
import inspect import os import sys from functools import partial, update_wrapper from types import MethodType from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Type, TypeVar, Union import torch import yaml from lightning_utilities.core.imports import RequirementCache from lightning_utilities.core.rank_zero import _warn from torch.optim import Optimizer from typing_extensions import override import lightning.pytorch as pl from lightning.fabric.utilities.cloud_io import get_filesystem from lightning.fabric.utilities.types import _TORCH_LRSCHEDULER from lightning.pytorch import Callback, LightningDataModule, LightningModule, Trainer, seed_everything from lightning.pytorch.core.mixins.hparams_mixin import _given_hyperparameters_context from lightning.pytorch.utilities.exceptions import MisconfigurationException from lightning.pytorch.utilities.model_helpers import is_overridden from lightning.pytorch.utilities.rank_zero import rank_zero_warn def _get_short_description(component: object) -> Optional[str]: if component.__doc__ is None: return None try: docstring = docstring_parser.parse(component.__doc__) return docstring.short_description except (ValueError, docstring_parser.ParseError) as ex: rank_zero_warn(f"Failed parsing docstring for {component}: {ex}")
null
155,358
import inspect import os import sys from functools import partial, update_wrapper from types import MethodType from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Type, TypeVar, Union import torch import yaml from lightning_utilities.core.imports import RequirementCache from lightning_utilities.core.rank_zero import _warn from torch.optim import Optimizer from typing_extensions import override import lightning.pytorch as pl from lightning.fabric.utilities.cloud_io import get_filesystem from lightning.fabric.utilities.types import _TORCH_LRSCHEDULER from lightning.pytorch import Callback, LightningDataModule, LightningModule, Trainer, seed_everything from lightning.pytorch.core.mixins.hparams_mixin import _given_hyperparameters_context from lightning.pytorch.utilities.exceptions import MisconfigurationException from lightning.pytorch.utilities.model_helpers import is_overridden from lightning.pytorch.utilities.rank_zero import rank_zero_warn def _get_module_type(value: Union[Callable, type]) -> type: if callable(value) and not isinstance(value, type): return inspect.signature(value).return_annotation return value
null
155,359
import inspect import os import sys from functools import partial, update_wrapper from types import MethodType from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Type, TypeVar, Union import torch import yaml from lightning_utilities.core.imports import RequirementCache from lightning_utilities.core.rank_zero import _warn from torch.optim import Optimizer from typing_extensions import override import lightning.pytorch as pl from lightning.fabric.utilities.cloud_io import get_filesystem from lightning.fabric.utilities.types import _TORCH_LRSCHEDULER from lightning.pytorch import Callback, LightningDataModule, LightningModule, Trainer, seed_everything from lightning.pytorch.core.mixins.hparams_mixin import _given_hyperparameters_context from lightning.pytorch.utilities.exceptions import MisconfigurationException from lightning.pytorch.utilities.model_helpers import is_overridden from lightning.pytorch.utilities.rank_zero import rank_zero_warn ModuleType = TypeVar("ModuleType") def instantiate_module(class_type: Type[ModuleType], config: Dict[str, Any]) -> ModuleType: parser = ArgumentParser(exit_on_error=False) if "class_path" in config: parser.add_subclass_arguments(class_type, "module") else: parser.add_class_arguments(class_type, "module") cfg = parser.parse_object({"module": config}) init = parser.instantiate_classes(cfg) return init.module
null
155,360
from typing import Optional, Union import lightning.pytorch as pl from lightning.fabric.utilities.warnings import PossibleUserWarning from lightning.pytorch.accelerators import CUDAAccelerator, MPSAccelerator, XLAAccelerator from lightning.pytorch.loggers.logger import DummyLogger from lightning.pytorch.profilers import ( AdvancedProfiler, PassThroughProfiler, Profiler, PyTorchProfiler, SimpleProfiler, XLAProfiler, ) from lightning.pytorch.utilities.exceptions import MisconfigurationException from lightning.pytorch.utilities.imports import _habana_available_and_importable from lightning.pytorch.utilities.rank_zero import rank_zero_info, rank_zero_warn def _determine_batch_limits(batches: Optional[Union[int, float]], name: str) -> Union[int, float]: if batches is None: # batches is optional to know if the user passed a value so that we can show the above info messages only to the # users that set a value explicitly return 1.0 # differentiating based on the type can be error-prone for users. show a message describing the chosen behaviour if isinstance(batches, int) and batches == 1: if name == "limit_train_batches": message = "1 batch per epoch will be used." elif name == "val_check_interval": message = "validation will run after every batch." else: message = "1 batch will be used." rank_zero_info(f"`Trainer({name}=1)` was configured so {message}") elif isinstance(batches, float) and batches == 1.0: if name == "limit_train_batches": message = "100% of the batches per epoch will be used." elif name == "val_check_interval": message = "validation will run at the end of the training epoch." else: message = "100% of the batches will be used." rank_zero_info(f"`Trainer({name}=1.0)` was configured so {message}.") if 0 <= batches <= 1: return batches if batches > 1 and batches % 1.0 == 0: return int(batches) raise MisconfigurationException( f"You have passed invalid value {batches} for {name}, it has to be in [0.0, 1.0] or an int." ) class DummyLogger(Logger): """Dummy logger for internal use. It is useful if we want to disable user's logger for a feature, but still ensure that user code can run """ def __init__(self) -> None: super().__init__() self._experiment = DummyExperiment() def experiment(self) -> DummyExperiment: """Return the experiment object associated with this logger.""" return self._experiment def log_metrics(self, *args: Any, **kwargs: Any) -> None: pass def log_hyperparams(self, *args: Any, **kwargs: Any) -> None: pass def name(self) -> str: """Return the experiment name.""" return "" def version(self) -> str: """Return the experiment version.""" return "" def __getitem__(self, idx: int) -> "DummyLogger": # enables self.logger[0].experiment.add_image(...) return self def __getattr__(self, name: str) -> Callable: """Allows the DummyLogger to be called with arbitrary methods, to avoid AttributeErrors.""" def method(*args: Any, **kwargs: Any) -> None: return None return method def _init_debugging_flags( trainer: "pl.Trainer", limit_train_batches: Optional[Union[int, float]], limit_val_batches: Optional[Union[int, float]], limit_test_batches: Optional[Union[int, float]], limit_predict_batches: Optional[Union[int, float]], fast_dev_run: Union[int, bool], overfit_batches: Union[int, float], val_check_interval: Optional[Union[int, float]], num_sanity_val_steps: int, ) -> None: # init debugging flags if isinstance(fast_dev_run, int) and (fast_dev_run < 0): raise MisconfigurationException( f"fast_dev_run={fast_dev_run!r} is not a valid configuration. It should be >= 0." ) trainer.fast_dev_run = fast_dev_run # set fast_dev_run=True when it is 1, used while logging if fast_dev_run == 1: trainer.fast_dev_run = True trainer.overfit_batches = _determine_batch_limits(overfit_batches, "overfit_batches") overfit_batches_enabled = overfit_batches > 0 if fast_dev_run: num_batches = int(fast_dev_run) if not overfit_batches_enabled: trainer.limit_train_batches = num_batches trainer.limit_val_batches = num_batches trainer.limit_test_batches = num_batches trainer.limit_predict_batches = num_batches trainer.fit_loop.epoch_loop.max_steps = num_batches trainer.num_sanity_val_steps = 0 trainer.fit_loop.max_epochs = 1 trainer.val_check_interval = 1.0 trainer.check_val_every_n_epoch = 1 trainer.loggers = [DummyLogger()] if trainer.loggers else [] rank_zero_info( f"Running in `fast_dev_run` mode: will run the requested loop using {num_batches} batch(es). " "Logging and checkpointing is suppressed." ) else: if not overfit_batches_enabled: trainer.limit_train_batches = _determine_batch_limits(limit_train_batches, "limit_train_batches") trainer.limit_val_batches = _determine_batch_limits(limit_val_batches, "limit_val_batches") trainer.limit_test_batches = _determine_batch_limits(limit_test_batches, "limit_test_batches") trainer.limit_predict_batches = _determine_batch_limits(limit_predict_batches, "limit_predict_batches") trainer.num_sanity_val_steps = float("inf") if num_sanity_val_steps == -1 else num_sanity_val_steps trainer.val_check_interval = _determine_batch_limits(val_check_interval, "val_check_interval") if overfit_batches_enabled: trainer.limit_train_batches = overfit_batches trainer.limit_val_batches = overfit_batches
null
155,361
from typing import Optional, Union import lightning.pytorch as pl from lightning.fabric.utilities.warnings import PossibleUserWarning from lightning.pytorch.accelerators import CUDAAccelerator, MPSAccelerator, XLAAccelerator from lightning.pytorch.loggers.logger import DummyLogger from lightning.pytorch.profilers import ( AdvancedProfiler, PassThroughProfiler, Profiler, PyTorchProfiler, SimpleProfiler, XLAProfiler, ) from lightning.pytorch.utilities.exceptions import MisconfigurationException from lightning.pytorch.utilities.imports import _habana_available_and_importable from lightning.pytorch.utilities.rank_zero import rank_zero_info, rank_zero_warn def _init_profiler(trainer: "pl.Trainer", profiler: Optional[Union[Profiler, str]]) -> None: if isinstance(profiler, str): PROFILERS = { "simple": SimpleProfiler, "advanced": AdvancedProfiler, "pytorch": PyTorchProfiler, "xla": XLAProfiler, } profiler = profiler.lower() if profiler not in PROFILERS: raise MisconfigurationException( "When passing string value for the `profiler` parameter of `Trainer`," f" it can only be one of {list(PROFILERS.keys())}" ) profiler_class = PROFILERS[profiler] profiler = profiler_class() trainer.profiler = profiler or PassThroughProfiler()
null
155,362
from typing import Optional, Union import lightning.pytorch as pl from lightning.fabric.utilities.warnings import PossibleUserWarning from lightning.pytorch.accelerators import CUDAAccelerator, MPSAccelerator, XLAAccelerator from lightning.pytorch.loggers.logger import DummyLogger from lightning.pytorch.profilers import ( AdvancedProfiler, PassThroughProfiler, Profiler, PyTorchProfiler, SimpleProfiler, XLAProfiler, ) from lightning.pytorch.utilities.exceptions import MisconfigurationException from lightning.pytorch.utilities.imports import _habana_available_and_importable from lightning.pytorch.utilities.rank_zero import rank_zero_info, rank_zero_warn class PossibleUserWarning(UserWarning): """Warnings that could be false positives.""" def _habana_available_and_importable() -> bool: # This is defined as a function instead of a constant to avoid circular imports, because `lightning_habana` # also imports Lightning return bool(_LIGHTNING_HABANA_AVAILABLE) and _try_import_module("lightning_habana") def _log_device_info(trainer: "pl.Trainer") -> None: if CUDAAccelerator.is_available(): gpu_available = True gpu_type = " (cuda)" elif MPSAccelerator.is_available(): gpu_available = True gpu_type = " (mps)" else: gpu_available = False gpu_type = "" gpu_used = isinstance(trainer.accelerator, (CUDAAccelerator, MPSAccelerator)) rank_zero_info(f"GPU available: {gpu_available}{gpu_type}, used: {gpu_used}") num_tpu_cores = trainer.num_devices if isinstance(trainer.accelerator, XLAAccelerator) else 0 rank_zero_info(f"TPU available: {XLAAccelerator.is_available()}, using: {num_tpu_cores} TPU cores") if _habana_available_and_importable(): from lightning_habana import HPUAccelerator num_hpus = trainer.num_devices if isinstance(trainer.accelerator, HPUAccelerator) else 0 hpu_available = HPUAccelerator.is_available() else: num_hpus = 0 hpu_available = False rank_zero_info(f"HPU available: {hpu_available}, using: {num_hpus} HPUs") if ( CUDAAccelerator.is_available() and not isinstance(trainer.accelerator, CUDAAccelerator) or MPSAccelerator.is_available() and not isinstance(trainer.accelerator, MPSAccelerator) ): rank_zero_warn( "GPU available but not used. You can set it by doing `Trainer(accelerator='gpu')`.", category=PossibleUserWarning, ) if XLAAccelerator.is_available() and not isinstance(trainer.accelerator, XLAAccelerator): rank_zero_warn("TPU available but not used. You can set it by doing `Trainer(accelerator='tpu')`.") if _habana_available_and_importable(): from lightning_habana import HPUAccelerator if HPUAccelerator.is_available() and not isinstance(trainer.accelerator, HPUAccelerator): rank_zero_warn("HPU available but not used. You can set it by doing `Trainer(accelerator='hpu')`.")
null
155,363
import os from dataclasses import dataclass, field from typing import Any, Iterable, Optional, Tuple, Union import torch.multiprocessing as mp from torch.utils.data import BatchSampler, DataLoader, RandomSampler, Sampler, SequentialSampler from torch.utils.data.distributed import DistributedSampler import lightning.pytorch as pl from lightning.fabric.utilities.data import ( _auto_add_worker_init_fn, _replace_dunder_methods, _set_sampler_epoch, has_iterable_dataset, suggested_max_num_workers, ) from lightning.fabric.utilities.distributed import DistributedSamplerWrapper, _InfiniteBarrier from lightning.pytorch.overrides.distributed import UnrepeatedDistributedSamplerWrapper from lightning.pytorch.trainer import call from lightning.pytorch.trainer.states import RunningStage, TrainerFn from lightning.pytorch.utilities.combined_loader import CombinedLoader from lightning.pytorch.utilities.data import _is_dataloader_shuffled, _update_dataloader from lightning.pytorch.utilities.exceptions import MisconfigurationException from lightning.pytorch.utilities.model_helpers import is_overridden from lightning.pytorch.utilities.rank_zero import WarningCache, rank_zero_warn from lightning.pytorch.utilities.types import EVAL_DATALOADERS, TRAIN_DATALOADERS from lightning.pytorch.utilities.warnings import PossibleUserWarning class DistributedSamplerWrapper(DistributedSampler): """Wrapper over ``Sampler`` for distributed training. Allows you to use any sampler in distributed mode. It will be automatically used by Lightning in distributed mode if sampler replacement is enabled. Note: The purpose of this wrapper is to take care of sharding the sampler indices. It is up to the underlying sampler to handle randomness and shuffling. The ``shuffle`` and ``seed`` arguments on this wrapper won't have any effect. """ def __init__(self, sampler: Union[Sampler, Iterable], *args: Any, **kwargs: Any) -> None: super().__init__(_DatasetSamplerWrapper(sampler), *args, **kwargs) def __iter__(self) -> Iterator: self.dataset.reset() return (self.dataset[index] for index in super().__iter__()) class UnrepeatedDistributedSamplerWrapper(UnrepeatedDistributedSampler): """Equivalent class to ``DistributedSamplerWrapper`` but for the ``UnrepeatedDistributedSampler``.""" def __init__(self, sampler: Union[Sampler, Iterable], *args: Any, **kwargs: Any) -> None: super().__init__(_DatasetSamplerWrapper(sampler), *args, **kwargs) def __iter__(self) -> Iterator: self.dataset.reset() return (self.dataset[index] for index in super().__iter__()) class RunningStage(LightningEnum): """Enum for the current running stage. This stage complements :class:`TrainerFn` by specifying the current running stage for each function. More than one running stage value can be set while a :class:`TrainerFn` is running: - ``TrainerFn.FITTING`` - ``RunningStage.{SANITY_CHECKING,TRAINING,VALIDATING}`` - ``TrainerFn.VALIDATING`` - ``RunningStage.VALIDATING`` - ``TrainerFn.TESTING`` - ``RunningStage.TESTING`` - ``TrainerFn.PREDICTING`` - ``RunningStage.PREDICTING`` """ TRAINING = "train" SANITY_CHECKING = "sanity_check" VALIDATING = "validate" TESTING = "test" PREDICTING = "predict" def evaluating(self) -> bool: return self in (self.VALIDATING, self.TESTING, self.SANITY_CHECKING) def dataloader_prefix(self) -> Optional[str]: if self in (self.VALIDATING, self.SANITY_CHECKING): return "val" return self.value The provided code snippet includes necessary dependencies for implementing the `_get_distributed_sampler` function. Write a Python function `def _get_distributed_sampler( dataloader: DataLoader, shuffle: bool, overfit_batches: Union[int, float], mode: Optional[RunningStage] = None, **kwargs: Any, ) -> DistributedSampler` to solve the following problem: This function is used to created the distributed sampler injected within the user DataLoader. Here is the function: def _get_distributed_sampler( dataloader: DataLoader, shuffle: bool, overfit_batches: Union[int, float], mode: Optional[RunningStage] = None, **kwargs: Any, ) -> DistributedSampler: """This function is used to created the distributed sampler injected within the user DataLoader.""" kwargs["shuffle"] = shuffle and not overfit_batches kwargs.setdefault("seed", int(os.getenv("PL_GLOBAL_SEED", 0))) if mode == RunningStage.PREDICTING: return UnrepeatedDistributedSamplerWrapper(dataloader.sampler, **kwargs) if isinstance(dataloader.sampler, (RandomSampler, SequentialSampler)): return DistributedSampler(dataloader.dataset, **kwargs) return DistributedSamplerWrapper(dataloader.sampler, **kwargs)
This function is used to created the distributed sampler injected within the user DataLoader.
155,364
import os from dataclasses import dataclass, field from typing import Any, Iterable, Optional, Tuple, Union import torch.multiprocessing as mp from torch.utils.data import BatchSampler, DataLoader, RandomSampler, Sampler, SequentialSampler from torch.utils.data.distributed import DistributedSampler import lightning.pytorch as pl from lightning.fabric.utilities.data import ( _auto_add_worker_init_fn, _replace_dunder_methods, _set_sampler_epoch, has_iterable_dataset, suggested_max_num_workers, ) from lightning.fabric.utilities.distributed import DistributedSamplerWrapper, _InfiniteBarrier from lightning.pytorch.overrides.distributed import UnrepeatedDistributedSamplerWrapper from lightning.pytorch.trainer import call from lightning.pytorch.trainer.states import RunningStage, TrainerFn from lightning.pytorch.utilities.combined_loader import CombinedLoader from lightning.pytorch.utilities.data import _is_dataloader_shuffled, _update_dataloader from lightning.pytorch.utilities.exceptions import MisconfigurationException from lightning.pytorch.utilities.model_helpers import is_overridden from lightning.pytorch.utilities.rank_zero import WarningCache, rank_zero_warn from lightning.pytorch.utilities.types import EVAL_DATALOADERS, TRAIN_DATALOADERS from lightning.pytorch.utilities.warnings import PossibleUserWarning class RunningStage(LightningEnum): """Enum for the current running stage. This stage complements :class:`TrainerFn` by specifying the current running stage for each function. More than one running stage value can be set while a :class:`TrainerFn` is running: - ``TrainerFn.FITTING`` - ``RunningStage.{SANITY_CHECKING,TRAINING,VALIDATING}`` - ``TrainerFn.VALIDATING`` - ``RunningStage.VALIDATING`` - ``TrainerFn.TESTING`` - ``RunningStage.TESTING`` - ``TrainerFn.PREDICTING`` - ``RunningStage.PREDICTING`` """ TRAINING = "train" SANITY_CHECKING = "sanity_check" VALIDATING = "validate" TESTING = "test" PREDICTING = "predict" def evaluating(self) -> bool: return self in (self.VALIDATING, self.TESTING, self.SANITY_CHECKING) def dataloader_prefix(self) -> Optional[str]: if self in (self.VALIDATING, self.SANITY_CHECKING): return "val" return self.value class CombinedLoader(Iterable): """Combines different iterables under specific sampling modes. Args: iterables: the iterable or collection of iterables to sample from. mode: the mode to use. The following modes are supported: * ``min_size``: stops after the shortest iterable (the one with the lowest number of items) is done. * ``max_size_cycle``: stops after the longest iterable (the one with most items) is done, while cycling through the rest of the iterables. * ``max_size``: stops after the longest iterable (the one with most items) is done, while returning None for the exhausted iterables. * ``sequential``: completely consumes each iterable sequentially, and returns a triplet ``(data, idx, iterable_idx)`` Examples: >>> from torch.utils.data import DataLoader >>> iterables = {'a': DataLoader(range(6), batch_size=4), ... 'b': DataLoader(range(15), batch_size=5)} >>> combined_loader = CombinedLoader(iterables, 'max_size_cycle') >>> _ = iter(combined_loader) >>> len(combined_loader) 3 >>> for batch, batch_idx, dataloader_idx in combined_loader: ... print(f"{batch}, {batch_idx=}, {dataloader_idx=}") {'a': tensor([0, 1, 2, 3]), 'b': tensor([0, 1, 2, 3, 4])}, batch_idx=0, dataloader_idx=0 {'a': tensor([4, 5]), 'b': tensor([5, 6, 7, 8, 9])}, batch_idx=1, dataloader_idx=0 {'a': tensor([0, 1, 2, 3]), 'b': tensor([10, 11, 12, 13, 14])}, batch_idx=2, dataloader_idx=0 >>> combined_loader = CombinedLoader(iterables, 'max_size') >>> _ = iter(combined_loader) >>> len(combined_loader) 3 >>> for batch, batch_idx, dataloader_idx in combined_loader: ... print(f"{batch}, {batch_idx=}, {dataloader_idx=}") {'a': tensor([0, 1, 2, 3]), 'b': tensor([0, 1, 2, 3, 4])}, batch_idx=0, dataloader_idx=0 {'a': tensor([4, 5]), 'b': tensor([5, 6, 7, 8, 9])}, batch_idx=1, dataloader_idx=0 {'a': None, 'b': tensor([10, 11, 12, 13, 14])}, batch_idx=2, dataloader_idx=0 >>> combined_loader = CombinedLoader(iterables, 'min_size') >>> _ = iter(combined_loader) >>> len(combined_loader) 2 >>> for batch, batch_idx, dataloader_idx in combined_loader: ... print(f"{batch}, {batch_idx=}, {dataloader_idx=}") {'a': tensor([0, 1, 2, 3]), 'b': tensor([0, 1, 2, 3, 4])}, batch_idx=0, dataloader_idx=0 {'a': tensor([4, 5]), 'b': tensor([5, 6, 7, 8, 9])}, batch_idx=1, dataloader_idx=0 >>> combined_loader = CombinedLoader(iterables, 'sequential') >>> _ = iter(combined_loader) >>> len(combined_loader) 5 >>> for batch, batch_idx, dataloader_idx in combined_loader: ... print(f"{batch}, {batch_idx=}, {dataloader_idx=}") tensor([0, 1, 2, 3]), batch_idx=0, dataloader_idx=0 tensor([4, 5]), batch_idx=1, dataloader_idx=0 tensor([0, 1, 2, 3, 4]), batch_idx=0, dataloader_idx=1 tensor([5, 6, 7, 8, 9]), batch_idx=1, dataloader_idx=1 tensor([10, 11, 12, 13, 14]), batch_idx=2, dataloader_idx=1 """ def __init__(self, iterables: Any, mode: _LITERAL_SUPPORTED_MODES = "min_size") -> None: if mode not in _SUPPORTED_MODES: raise ValueError(f"Unsupported mode {mode!r}, please select one of: {list(_SUPPORTED_MODES)}.") self._iterables = iterables self._flattened, self._spec = _tree_flatten(iterables) self._mode = mode self._iterator: Optional[_ModeIterator] = None self._limits: Optional[List[Union[int, float]]] = None def iterables(self) -> Any: """Return the original collection of iterables.""" return self._iterables def sampler(self) -> Any: """Return a collections of samplers extracted from iterables.""" return _map_and_unflatten(lambda x: getattr(x, "sampler", None), self.flattened, self._spec) def batch_sampler(self) -> Any: """Return a collections of batch samplers extracted from iterables.""" return _map_and_unflatten(lambda x: getattr(x, "batch_sampler", None), self.flattened, self._spec) def flattened(self) -> List[Any]: """Return the flat list of iterables.""" return self._flattened def flattened(self, flattened: List[Any]) -> None: """Setter to conveniently update the list of iterables.""" if len(flattened) != len(self._flattened): raise ValueError( f"Mismatch in flattened length ({len(flattened)}) and existing length ({len(self._flattened)})" ) # update the iterable collection self._iterables = tree_unflatten(flattened, self._spec) self._flattened = flattened def limits(self) -> Optional[List[Union[int, float]]]: """Optional limits per iterator.""" return self._limits def limits(self, limits: Optional[Union[int, float, List[Union[int, float]]]]) -> None: if isinstance(limits, (int, float)): limits = [limits] * len(self.flattened) elif isinstance(limits, list) and len(limits) != len(self.flattened): raise ValueError( f"Mismatch in number of limits ({len(limits)}) and number of iterables ({len(self.flattened)})" ) self._limits = limits def __next__(self) -> _ITERATOR_RETURN: assert self._iterator is not None out = next(self._iterator) if isinstance(self._iterator, _Sequential): return out out, batch_idx, dataloader_idx = out return tree_unflatten(out, self._spec), batch_idx, dataloader_idx def __iter__(self) -> Self: cls = _SUPPORTED_MODES[self._mode]["iterator"] iterator = cls(self.flattened, self._limits) iter(iterator) self._iterator = iterator return self def __len__(self) -> int: """Compute the number of batches.""" if self._iterator is None: raise RuntimeError("Please call `iter(combined_loader)` first.") return len(self._iterator) def reset(self) -> None: """Reset the state and shutdown any workers.""" if self._iterator is not None: self._iterator.reset() self._iterator = None for iterable in self.flattened: _shutdown_workers_and_reset_iterator(iterable) def _dataset_length(self) -> int: """Compute the total length of the datasets according to the current mode.""" datasets = [getattr(dl, "dataset", None) for dl in self.flattened] lengths = [length for ds in datasets if (length := sized_len(ds)) is not None] if not lengths: raise NotImplementedError("All datasets are iterable-style datasets.") fn = _SUPPORTED_MODES[self._mode]["fn"] return fn(lengths) def _state_dicts(self) -> List[Dict[str, Any]]: """Returns the list of state dicts for iterables in `self.flattened` that are stateful.""" return [loader.state_dict() for loader in self.flattened if isinstance(loader, _Stateful)] def _load_state_dicts(self, states: List[Dict[str, Any]]) -> None: """Loads the state dicts for iterables in `self.flattened` that are stateful.""" if not states: return stateful_loaders = [loader for loader in self.flattened if isinstance(loader, _Stateful)] if len(stateful_loaders) != len(states): raise RuntimeError( f"The CombinedLoader has {len(stateful_loaders)} stateful loaders, but found {len(states)} states" " in the checkpoint. Please make sure you define the same dataloaders that were used when saving" " the checkpoint." ) for loader, state_dict in zip(stateful_loaders, states): loader.load_state_dict(state_dict) def _update_dataloader( dataloader: DataLoader, sampler: Union[Sampler, Iterable], mode: Optional[RunningStage] = None ) -> DataLoader: dl_args, dl_kwargs = _get_dataloader_init_args_and_kwargs(dataloader, sampler, mode) return _reinstantiate_wrapped_cls(dataloader, *dl_args, **dl_kwargs) def _resolve_overfit_batches(combined_loader: CombinedLoader, mode: RunningStage) -> None: all_have_sequential_sampler = all( isinstance(dl.sampler, SequentialSampler) for dl in combined_loader.flattened if hasattr(dl, "sampler") ) if all_have_sequential_sampler: return rank_zero_warn( f"You requested to overfit but enabled {mode.dataloader_prefix} dataloader shuffling." f" We are turning off the {mode.dataloader_prefix} dataloader shuffling for you." ) updated = [ _update_dataloader(dl, sampler=SequentialSampler(dl.dataset), mode=mode) if hasattr(dl, "dataset") else dl for dl in combined_loader.flattened ] combined_loader.flattened = updated
null
155,365
import os from dataclasses import dataclass, field from typing import Any, Iterable, Optional, Tuple, Union import torch.multiprocessing as mp from torch.utils.data import BatchSampler, DataLoader, RandomSampler, Sampler, SequentialSampler from torch.utils.data.distributed import DistributedSampler import lightning.pytorch as pl from lightning.fabric.utilities.data import ( _auto_add_worker_init_fn, _replace_dunder_methods, _set_sampler_epoch, has_iterable_dataset, suggested_max_num_workers, ) from lightning.fabric.utilities.distributed import DistributedSamplerWrapper, _InfiniteBarrier from lightning.pytorch.overrides.distributed import UnrepeatedDistributedSamplerWrapper from lightning.pytorch.trainer import call from lightning.pytorch.trainer.states import RunningStage, TrainerFn from lightning.pytorch.utilities.combined_loader import CombinedLoader from lightning.pytorch.utilities.data import _is_dataloader_shuffled, _update_dataloader from lightning.pytorch.utilities.exceptions import MisconfigurationException from lightning.pytorch.utilities.model_helpers import is_overridden from lightning.pytorch.utilities.rank_zero import WarningCache, rank_zero_warn from lightning.pytorch.utilities.types import EVAL_DATALOADERS, TRAIN_DATALOADERS from lightning.pytorch.utilities.warnings import PossibleUserWarning class _DataLoaderSource: """Stores the information where the dataloaders come from. The source can be 1. from a ``*_dataloader()`` method on the :class:`~lightning.pytorch.core.LightningModule`, 2. from a ``*_dataloader()`` method on the :class:`~lightning.pytorch.core.datamodule.LightningDataModule`, 3. a direct instance of a :class:`~torch.utils.data.DataLoader` or supported collections thereof. Arguments: instance: A LightningModule, LightningDataModule, or (a collection of) iterable(s). name: A name for this dataloader source. If the instance is a module, the name corresponds to the hook that returns the desired dataloader(s). """ instance: Optional[Union[TRAIN_DATALOADERS, EVAL_DATALOADERS, "pl.LightningModule", "pl.LightningDataModule"]] name: str def dataloader(self) -> Union[TRAIN_DATALOADERS, EVAL_DATALOADERS]: """Returns the dataloader from the source. If the source is a module, the method with the corresponding :attr:`name` gets called. """ if isinstance(self.instance, pl.LightningModule): return call._call_lightning_module_hook(self.instance.trainer, self.name, pl_module=self.instance) if isinstance(self.instance, pl.LightningDataModule): assert self.instance.trainer is not None return call._call_lightning_datamodule_hook(self.instance.trainer, self.name) assert self.instance is not None return self.instance def is_defined(self) -> bool: """Returns whether the source dataloader can be retrieved or not. If the source is a module it checks that the method with given :attr:`name` is overridden. """ return not self.is_module() or is_overridden(self.name, self.instance) def is_module(self) -> bool: """Returns whether the DataLoader source is a LightningModule or a LightningDataModule. It does not check whether ``*_dataloader`` methods are actually overridden. """ return isinstance(self.instance, (pl.LightningModule, pl.LightningDataModule)) def _replace_dunder_methods(base_cls: Type, store_explicit_arg: Optional[str] = None) -> Generator[None, None, None]: """This context manager is used to add support for re-instantiation of custom (subclasses) of `base_cls`. It patches the ``__init__``, ``__setattr__`` and ``__delattr__`` methods. """ classes = get_all_subclasses(base_cls) | {base_cls} for cls in classes: # Check that __init__ belongs to the class # https://stackoverflow.com/a/5253424 if "__init__" in cls.__dict__: cls.__old__init__ = cls.__init__ cls.__init__ = _wrap_init_method(cls.__init__, store_explicit_arg) # we want at least one setattr/delattr in the chain to be patched and it can happen, that none of the subclasses # implement `__setattr__`/`__delattr__`. Therefore, we are always patching the `base_cls` for patch_fn_name, tag in (("__setattr__", _WrapAttrTag.SET), ("__delattr__", _WrapAttrTag.DEL)): if patch_fn_name in cls.__dict__ or cls is base_cls: saved_name = f"__old{patch_fn_name}" setattr(cls, saved_name, getattr(cls, patch_fn_name)) setattr(cls, patch_fn_name, _wrap_attr_method(getattr(cls, patch_fn_name), tag)) yield for cls in classes: for patched_name in ("__setattr__", "__delattr__", "__init__"): # Check that __old__{init,setattr,delattr} belongs to the class # https://stackoverflow.com/a/5253424 if f"__old{patched_name}" in cls.__dict__: setattr(cls, patched_name, getattr(cls, f"__old{patched_name}")) delattr(cls, f"__old{patched_name}") TRAIN_DATALOADERS = Any EVAL_DATALOADERS = Any The provided code snippet includes necessary dependencies for implementing the `_request_dataloader` function. Write a Python function `def _request_dataloader(data_source: _DataLoaderSource) -> Union[TRAIN_DATALOADERS, EVAL_DATALOADERS]` to solve the following problem: Requests a dataloader by calling dataloader hooks corresponding to the given stage. Returns: The requested dataloader Here is the function: def _request_dataloader(data_source: _DataLoaderSource) -> Union[TRAIN_DATALOADERS, EVAL_DATALOADERS]: """Requests a dataloader by calling dataloader hooks corresponding to the given stage. Returns: The requested dataloader """ with _replace_dunder_methods(DataLoader, "dataset"), _replace_dunder_methods(BatchSampler): # under this context manager, the arguments passed to `DataLoader.__init__` will be captured and saved as # attributes on the instance in case the dataloader needs to be re-instantiated later by Lightning. # Also, it records all attribute setting and deletion using patched `__setattr__` and `__delattr__` # methods so that the re-instantiated object is as close to the original as possible. return data_source.dataloader()
Requests a dataloader by calling dataloader hooks corresponding to the given stage. Returns: The requested dataloader
155,366
import os from dataclasses import dataclass, field from typing import Any, Iterable, Optional, Tuple, Union import torch.multiprocessing as mp from torch.utils.data import BatchSampler, DataLoader, RandomSampler, Sampler, SequentialSampler from torch.utils.data.distributed import DistributedSampler import lightning.pytorch as pl from lightning.fabric.utilities.data import ( _auto_add_worker_init_fn, _replace_dunder_methods, _set_sampler_epoch, has_iterable_dataset, suggested_max_num_workers, ) from lightning.fabric.utilities.distributed import DistributedSamplerWrapper, _InfiniteBarrier from lightning.pytorch.overrides.distributed import UnrepeatedDistributedSamplerWrapper from lightning.pytorch.trainer import call from lightning.pytorch.trainer.states import RunningStage, TrainerFn from lightning.pytorch.utilities.combined_loader import CombinedLoader from lightning.pytorch.utilities.data import _is_dataloader_shuffled, _update_dataloader from lightning.pytorch.utilities.exceptions import MisconfigurationException from lightning.pytorch.utilities.model_helpers import is_overridden from lightning.pytorch.utilities.rank_zero import WarningCache, rank_zero_warn from lightning.pytorch.utilities.types import EVAL_DATALOADERS, TRAIN_DATALOADERS from lightning.pytorch.utilities.warnings import PossibleUserWarning class _DataLoaderSource: """Stores the information where the dataloaders come from. The source can be 1. from a ``*_dataloader()`` method on the :class:`~lightning.pytorch.core.LightningModule`, 2. from a ``*_dataloader()`` method on the :class:`~lightning.pytorch.core.datamodule.LightningDataModule`, 3. a direct instance of a :class:`~torch.utils.data.DataLoader` or supported collections thereof. Arguments: instance: A LightningModule, LightningDataModule, or (a collection of) iterable(s). name: A name for this dataloader source. If the instance is a module, the name corresponds to the hook that returns the desired dataloader(s). """ instance: Optional[Union[TRAIN_DATALOADERS, EVAL_DATALOADERS, "pl.LightningModule", "pl.LightningDataModule"]] name: str def dataloader(self) -> Union[TRAIN_DATALOADERS, EVAL_DATALOADERS]: """Returns the dataloader from the source. If the source is a module, the method with the corresponding :attr:`name` gets called. """ if isinstance(self.instance, pl.LightningModule): return call._call_lightning_module_hook(self.instance.trainer, self.name, pl_module=self.instance) if isinstance(self.instance, pl.LightningDataModule): assert self.instance.trainer is not None return call._call_lightning_datamodule_hook(self.instance.trainer, self.name) assert self.instance is not None return self.instance def is_defined(self) -> bool: """Returns whether the source dataloader can be retrieved or not. If the source is a module it checks that the method with given :attr:`name` is overridden. """ return not self.is_module() or is_overridden(self.name, self.instance) def is_module(self) -> bool: """Returns whether the DataLoader source is a LightningModule or a LightningDataModule. It does not check whether ``*_dataloader`` methods are actually overridden. """ return isinstance(self.instance, (pl.LightningModule, pl.LightningDataModule)) class TrainerFn(LightningEnum): """Enum for the user-facing functions of the :class:`~lightning.pytorch.trainer.trainer.Trainer` such as :meth:`~lightning.pytorch.trainer.trainer.Trainer.fit` and :meth:`~lightning.pytorch.trainer.trainer.Trainer.test`.""" FITTING = "fit" VALIDATING = "validate" TESTING = "test" PREDICTING = "predict" def is_overridden(method_name: str, instance: Optional[object] = None, parent: Optional[Type[object]] = None) -> bool: if instance is None: # if `self.lightning_module` was passed as instance, it can be `None` return False if parent is None: if isinstance(instance, pl.LightningModule): parent = pl.LightningModule elif isinstance(instance, pl.LightningDataModule): parent = pl.LightningDataModule elif isinstance(instance, pl.Callback): parent = pl.Callback if parent is None: _check_mixed_imports(instance) raise ValueError("Expected a parent") from lightning_utilities.core.overrides import is_overridden as _is_overridden return _is_overridden(method_name, instance, parent) def _check_dataloader_iterable( dataloader: object, source: _DataLoaderSource, trainer_fn: TrainerFn, ) -> None: if isinstance(dataloader, DataLoader): # Fast path: `torch.utils.data.DataLoader` is always iterable, calling iter() would be expensive return try: iter(dataloader) # type: ignore[call-overload] except TypeError: # A prefix in the message to disambiguate between the train- and (optional) val dataloader that .fit() accepts prefix = "train_" if trainer_fn == TrainerFn.FITTING else "" if not source.is_module(): raise TypeError( f"An invalid dataloader was passed to `Trainer.{trainer_fn.value}({prefix}dataloaders=...)`." f" Found {dataloader}." ) if not is_overridden(source.name, source.instance): raise TypeError( f"An invalid dataloader was passed to `Trainer.{trainer_fn.value}({prefix}dataloaders=...)`." f" Found {dataloader}." f" Either pass the dataloader to the `.{trainer_fn.value}()` method OR implement" f" `def {source.name}(self):` in your LightningModule/LightningDataModule." ) raise TypeError( f"An invalid dataloader was returned from `{type(source.instance).__name__}.{source.name}()`." f" Found {dataloader}." )
null
155,367
import os from dataclasses import dataclass, field from typing import Any, Iterable, Optional, Tuple, Union import torch.multiprocessing as mp from torch.utils.data import BatchSampler, DataLoader, RandomSampler, Sampler, SequentialSampler from torch.utils.data.distributed import DistributedSampler import lightning.pytorch as pl from lightning.fabric.utilities.data import ( _auto_add_worker_init_fn, _replace_dunder_methods, _set_sampler_epoch, has_iterable_dataset, suggested_max_num_workers, ) from lightning.fabric.utilities.distributed import DistributedSamplerWrapper, _InfiniteBarrier from lightning.pytorch.overrides.distributed import UnrepeatedDistributedSamplerWrapper from lightning.pytorch.trainer import call from lightning.pytorch.trainer.states import RunningStage, TrainerFn from lightning.pytorch.utilities.combined_loader import CombinedLoader from lightning.pytorch.utilities.data import _is_dataloader_shuffled, _update_dataloader from lightning.pytorch.utilities.exceptions import MisconfigurationException from lightning.pytorch.utilities.model_helpers import is_overridden from lightning.pytorch.utilities.rank_zero import WarningCache, rank_zero_warn from lightning.pytorch.utilities.types import EVAL_DATALOADERS, TRAIN_DATALOADERS from lightning.pytorch.utilities.warnings import PossibleUserWarning class RunningStage(LightningEnum): """Enum for the current running stage. This stage complements :class:`TrainerFn` by specifying the current running stage for each function. More than one running stage value can be set while a :class:`TrainerFn` is running: - ``TrainerFn.FITTING`` - ``RunningStage.{SANITY_CHECKING,TRAINING,VALIDATING}`` - ``TrainerFn.VALIDATING`` - ``RunningStage.VALIDATING`` - ``TrainerFn.TESTING`` - ``RunningStage.TESTING`` - ``TrainerFn.PREDICTING`` - ``RunningStage.PREDICTING`` """ TRAINING = "train" SANITY_CHECKING = "sanity_check" VALIDATING = "validate" TESTING = "test" PREDICTING = "predict" def evaluating(self) -> bool: return self in (self.VALIDATING, self.TESTING, self.SANITY_CHECKING) def dataloader_prefix(self) -> Optional[str]: if self in (self.VALIDATING, self.SANITY_CHECKING): return "val" return self.value def _parse_num_batches( stage: RunningStage, length: Union[int, float], limit_batches: Union[int, float] ) -> Union[int, float]: if length == 0: return int(length) num_batches = length # limit num batches either as a percent or num steps if isinstance(limit_batches, int): num_batches = min(length, limit_batches) elif isinstance(limit_batches, float) and length != float("inf"): num_batches = int(length * limit_batches) elif limit_batches != 1.0: raise MisconfigurationException( f"When using an `IterableDataset`, `Trainer(limit_{stage.dataloader_prefix}_batches)` must be" f" `1.0` or an int. An int specifies `num_{stage.dataloader_prefix}_batches` to use." ) if num_batches == 0 and limit_batches > 0.0 and isinstance(limit_batches, float) and length != float("inf"): min_percentage = 1.0 / length raise MisconfigurationException( f"You requested to check {limit_batches} of the `{stage.dataloader_prefix}_dataloader` but" f" {limit_batches} * {length} < 1. Please increase the" f" `limit_{stage.dataloader_prefix}_batches` argument. Try at least" f" `limit_{stage.dataloader_prefix}_batches={min_percentage}`" ) return num_batches
null
155,368
import os from dataclasses import dataclass, field from typing import Any, Iterable, Optional, Tuple, Union import torch.multiprocessing as mp from torch.utils.data import BatchSampler, DataLoader, RandomSampler, Sampler, SequentialSampler from torch.utils.data.distributed import DistributedSampler import lightning.pytorch as pl from lightning.fabric.utilities.data import ( _auto_add_worker_init_fn, _replace_dunder_methods, _set_sampler_epoch, has_iterable_dataset, suggested_max_num_workers, ) from lightning.fabric.utilities.distributed import DistributedSamplerWrapper, _InfiniteBarrier from lightning.pytorch.overrides.distributed import UnrepeatedDistributedSamplerWrapper from lightning.pytorch.trainer import call from lightning.pytorch.trainer.states import RunningStage, TrainerFn from lightning.pytorch.utilities.combined_loader import CombinedLoader from lightning.pytorch.utilities.data import _is_dataloader_shuffled, _update_dataloader from lightning.pytorch.utilities.exceptions import MisconfigurationException from lightning.pytorch.utilities.model_helpers import is_overridden from lightning.pytorch.utilities.rank_zero import WarningCache, rank_zero_warn from lightning.pytorch.utilities.types import EVAL_DATALOADERS, TRAIN_DATALOADERS from lightning.pytorch.utilities.warnings import PossibleUserWarning def _worker_check(trainer: "pl.Trainer", dataloader: object, name: str) -> None: if not isinstance(dataloader, DataLoader): return upper_bound = suggested_max_num_workers(trainer.num_devices) start_method = ( dataloader.multiprocessing_context.get_start_method() if dataloader.multiprocessing_context is not None else mp.get_start_method() ) if dataloader.num_workers > 0 and start_method == "spawn" and not dataloader.persistent_workers: rank_zero_warn( f"Consider setting `persistent_workers=True` in '{name}' to speed up the dataloader worker initialization." ) elif dataloader.num_workers < 2 and upper_bound > 1: # if changed, update the `filterwarnings` snippet in 'advanced/warnings.rst' rank_zero_warn( f"The '{name}' does not have many workers which may be a bottleneck. Consider increasing the value of the" f" `num_workers` argument` to `num_workers={upper_bound}` in the `DataLoader` to improve performance.", category=PossibleUserWarning, ) if dataloader.persistent_workers and dataloader.pin_memory and trainer.reload_dataloaders_every_n_epochs > 0: rank_zero_warn( "The combination of `DataLoader(`pin_memory=True`, `persistent_workers=True`) and `Trainer(" "reload_dataloaders_every_n_epochs > 0)` can lead to instability due to limitations in PyTorch" " (https://github.com/pytorch/pytorch/issues/91252). We recommend setting `pin_memory=False` in this case.", category=PossibleUserWarning, ) def _auto_add_worker_init_fn(dataloader: object, rank: int) -> None: if not hasattr(dataloader, "worker_init_fn"): return if int(os.environ.get("PL_SEED_WORKERS", 0)) and dataloader.worker_init_fn is None: dataloader.worker_init_fn = partial(pl_worker_init_function, rank=rank) def _set_sampler_epoch(dataloader: object, epoch: int) -> None: """Calls the ``set_epoch`` method on either the sampler of the given dataloader. Every PyTorch dataloader has either a sampler or a batch sampler. If the sampler is wrapped by a :class:`~torch.utils.data.distributed.DistributedSampler`, ``set_epoch`` must be called at the beginning of every epoch to ensure shuffling applies a new ordering. This has no effect if shuffling is off. """ # cannot use a set because samplers might be unhashable: use a dict based on the id to drop duplicates objects: Dict[int, Any] = {} # check dataloader.sampler if (sampler := getattr(dataloader, "sampler", None)) is not None: objects[id(sampler)] = sampler # check dataloader.batch_sampler.sampler if (batch_sampler := getattr(dataloader, "batch_sampler", None)) is not None and ( sampler := getattr(batch_sampler, "sampler", None) ) is not None: objects[id(sampler)] = sampler for obj in objects.values(): set_epoch = getattr(obj, "set_epoch", None) if callable(set_epoch): set_epoch(epoch) class TrainerFn(LightningEnum): """Enum for the user-facing functions of the :class:`~lightning.pytorch.trainer.trainer.Trainer` such as :meth:`~lightning.pytorch.trainer.trainer.Trainer.fit` and :meth:`~lightning.pytorch.trainer.trainer.Trainer.test`.""" FITTING = "fit" VALIDATING = "validate" TESTING = "test" PREDICTING = "predict" class RunningStage(LightningEnum): """Enum for the current running stage. This stage complements :class:`TrainerFn` by specifying the current running stage for each function. More than one running stage value can be set while a :class:`TrainerFn` is running: - ``TrainerFn.FITTING`` - ``RunningStage.{SANITY_CHECKING,TRAINING,VALIDATING}`` - ``TrainerFn.VALIDATING`` - ``RunningStage.VALIDATING`` - ``TrainerFn.TESTING`` - ``RunningStage.TESTING`` - ``TrainerFn.PREDICTING`` - ``RunningStage.PREDICTING`` """ TRAINING = "train" SANITY_CHECKING = "sanity_check" VALIDATING = "validate" TESTING = "test" PREDICTING = "predict" def evaluating(self) -> bool: return self in (self.VALIDATING, self.TESTING, self.SANITY_CHECKING) def dataloader_prefix(self) -> Optional[str]: if self in (self.VALIDATING, self.SANITY_CHECKING): return "val" return self.value def _is_dataloader_shuffled(dataloader: object) -> bool: if hasattr(dataloader, "__pl_saved_kwargs"): # this attribute is not part of PyTorch's DataLoader, but could have been set by # our `_replace_init_method` context manager if "shuffle" in dataloader.__pl_saved_kwargs: return dataloader.__pl_saved_kwargs["shuffle"] if "shuffle" in dataloader.__pl_saved_arg_names: return dataloader.__pl_saved_args[dataloader.__pl_saved_arg_names.index("shuffle")] if hasattr(dataloader, "dataset") and isinstance(dataloader.dataset, IterableDataset): # shuffling is useless with iterable datasets return False if not hasattr(dataloader, "sampler"): # shuffling is enabled via a sampler. No sampler, no shuffling return False sampler = dataloader.sampler if isinstance(sampler, SequentialSampler): return False return isinstance(sampler, RandomSampler) def _process_dataloader( trainer: "pl.Trainer", trainer_fn: TrainerFn, stage: RunningStage, dataloader: object ) -> object: if stage != RunningStage.TRAINING: is_shuffled = _is_dataloader_shuffled(dataloader) # limit this warning only for samplers assigned automatically when shuffle is set if is_shuffled: rank_zero_warn( f"Your `{stage.dataloader_prefix}_dataloader`'s sampler has shuffling enabled," " it is strongly recommended that you turn shuffling off for val/test dataloaders.", category=PossibleUserWarning, ) else: is_shuffled = True # automatically add samplers dataloader = trainer._data_connector._prepare_dataloader(dataloader, shuffle=is_shuffled, mode=stage) # let the strategy inject its logic dataloader = trainer.strategy.process_dataloader(dataloader) # check the workers _worker_check( trainer=trainer, dataloader=dataloader, name=f"{stage.dataloader_prefix}_dataloader", ) # add worker_init_fn for correct seeding in worker processes _auto_add_worker_init_fn(dataloader, trainer.global_rank) if trainer_fn != TrainerFn.FITTING: # if we are fitting, we need to do this in the loop # some users want validation shuffling based on the training progress _set_sampler_epoch(dataloader, trainer.fit_loop.epoch_progress.current.processed) return dataloader
null
155,369
import logging import os from collections import Counter from typing import Dict, List, Literal, Optional, Union import torch from lightning.fabric.connector import _PRECISION_INPUT, _PRECISION_INPUT_STR, _convert_precision_to_unified_args from lightning.fabric.plugins.environments import ( ClusterEnvironment, LightningEnvironment, LSFEnvironment, MPIEnvironment, SLURMEnvironment, TorchElasticEnvironment, ) from lightning.fabric.utilities.device_parser import _determine_root_gpu_device from lightning.fabric.utilities.imports import _IS_INTERACTIVE from lightning.pytorch.accelerators import AcceleratorRegistry from lightning.pytorch.accelerators.accelerator import Accelerator from lightning.pytorch.accelerators.cuda import CUDAAccelerator from lightning.pytorch.accelerators.mps import MPSAccelerator from lightning.pytorch.accelerators.xla import XLAAccelerator from lightning.pytorch.plugins import ( _PLUGIN_INPUT, BitsandbytesPrecision, CheckpointIO, DeepSpeedPrecision, DoublePrecision, FSDPPrecision, HalfPrecision, MixedPrecision, Precision, TransformerEnginePrecision, XLAPrecision, ) from lightning.pytorch.plugins.layer_sync import LayerSync, TorchSyncBatchNorm from lightning.pytorch.strategies import ( DDPStrategy, DeepSpeedStrategy, FSDPStrategy, ParallelStrategy, SingleDeviceStrategy, SingleDeviceXLAStrategy, Strategy, StrategyRegistry, XLAStrategy, ) from lightning.pytorch.strategies.ddp import _DDP_FORK_ALIASES from lightning.pytorch.utilities.exceptions import MisconfigurationException from lightning.pytorch.utilities.imports import _habana_available_and_importable from lightning.pytorch.utilities.rank_zero import rank_zero_info, rank_zero_warn _LITERAL_WARN = Literal["warn"] def _set_torch_flags( *, deterministic: Optional[Union[bool, _LITERAL_WARN]] = None, benchmark: Optional[bool] = None ) -> None: if deterministic: if benchmark is None: # Set benchmark to False to ensure determinism benchmark = False elif benchmark: rank_zero_warn( "You passed `deterministic=True` and `benchmark=True`. Note that PyTorch ignores" " torch.backends.cudnn.deterministic=True when torch.backends.cudnn.benchmark=True.", ) if benchmark is not None: torch.backends.cudnn.benchmark = benchmark if deterministic == "warn": torch.use_deterministic_algorithms(True, warn_only=True) elif isinstance(deterministic, bool): # do not call this if deterministic wasn't passed torch.use_deterministic_algorithms(deterministic) if deterministic: # https://docs.nvidia.com/cuda/cublas/index.html#cublasApi_reproducibility os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
null
155,370
import logging import os from collections import Counter from typing import Dict, List, Literal, Optional, Union import torch from lightning.fabric.connector import _PRECISION_INPUT, _PRECISION_INPUT_STR, _convert_precision_to_unified_args from lightning.fabric.plugins.environments import ( ClusterEnvironment, LightningEnvironment, LSFEnvironment, MPIEnvironment, SLURMEnvironment, TorchElasticEnvironment, ) from lightning.fabric.utilities.device_parser import _determine_root_gpu_device from lightning.fabric.utilities.imports import _IS_INTERACTIVE from lightning.pytorch.accelerators import AcceleratorRegistry from lightning.pytorch.accelerators.accelerator import Accelerator from lightning.pytorch.accelerators.cuda import CUDAAccelerator from lightning.pytorch.accelerators.mps import MPSAccelerator from lightning.pytorch.accelerators.xla import XLAAccelerator from lightning.pytorch.plugins import ( _PLUGIN_INPUT, BitsandbytesPrecision, CheckpointIO, DeepSpeedPrecision, DoublePrecision, FSDPPrecision, HalfPrecision, MixedPrecision, Precision, TransformerEnginePrecision, XLAPrecision, ) from lightning.pytorch.plugins.layer_sync import LayerSync, TorchSyncBatchNorm from lightning.pytorch.strategies import ( DDPStrategy, DeepSpeedStrategy, FSDPStrategy, ParallelStrategy, SingleDeviceStrategy, SingleDeviceXLAStrategy, Strategy, StrategyRegistry, XLAStrategy, ) from lightning.pytorch.strategies.ddp import _DDP_FORK_ALIASES from lightning.pytorch.utilities.exceptions import MisconfigurationException from lightning.pytorch.utilities.imports import _habana_available_and_importable from lightning.pytorch.utilities.rank_zero import rank_zero_info, rank_zero_warn AcceleratorRegistry = _AcceleratorRegistry() StrategyRegistry = _StrategyRegistry() def _habana_available_and_importable() -> bool: # This is defined as a function instead of a constant to avoid circular imports, because `lightning_habana` # also imports Lightning return bool(_LIGHTNING_HABANA_AVAILABLE) and _try_import_module("lightning_habana") The provided code snippet includes necessary dependencies for implementing the `_register_external_accelerators_and_strategies` function. Write a Python function `def _register_external_accelerators_and_strategies() -> None` to solve the following problem: Registers all known strategies in other packages. Here is the function: def _register_external_accelerators_and_strategies() -> None: """Registers all known strategies in other packages.""" if _habana_available_and_importable(): from lightning_habana import HPUAccelerator, HPUParallelStrategy, SingleHPUStrategy # TODO: Prevent registering multiple times if "hpu" not in AcceleratorRegistry: HPUAccelerator.register_accelerators(AcceleratorRegistry) if "hpu_parallel" not in StrategyRegistry: HPUParallelStrategy.register_strategies(StrategyRegistry) if "hpu_single" not in StrategyRegistry: SingleHPUStrategy.register_strategies(StrategyRegistry)
Registers all known strategies in other packages.
155,371
import logging import os from datetime import timedelta from typing import Dict, List, Optional, Sequence, Union import lightning.pytorch as pl from lightning.fabric.utilities.registry import _load_external_callbacks from lightning.pytorch.callbacks import ( Callback, Checkpoint, ModelCheckpoint, ModelSummary, ProgressBar, RichProgressBar, TQDMProgressBar, ) from lightning.pytorch.callbacks.batch_size_finder import BatchSizeFinder from lightning.pytorch.callbacks.lr_finder import LearningRateFinder from lightning.pytorch.callbacks.rich_model_summary import RichModelSummary from lightning.pytorch.callbacks.timer import Timer from lightning.pytorch.trainer import call from lightning.pytorch.utilities.exceptions import MisconfigurationException from lightning.pytorch.utilities.model_helpers import is_overridden from lightning.pytorch.utilities.rank_zero import rank_zero_info def is_overridden(method_name: str, instance: Optional[object] = None, parent: Optional[Type[object]] = None) -> bool: if instance is None: # if `self.lightning_module` was passed as instance, it can be `None` return False if parent is None: if isinstance(instance, pl.LightningModule): parent = pl.LightningModule elif isinstance(instance, pl.LightningDataModule): parent = pl.LightningDataModule elif isinstance(instance, pl.Callback): parent = pl.Callback if parent is None: _check_mixed_imports(instance) raise ValueError("Expected a parent") from lightning_utilities.core.overrides import is_overridden as _is_overridden return _is_overridden(method_name, instance, parent) def _validate_callbacks_list(callbacks: List[Callback]) -> None: stateful_callbacks = [cb for cb in callbacks if is_overridden("state_dict", instance=cb)] seen_callbacks = set() for callback in stateful_callbacks: if callback.state_key in seen_callbacks: raise RuntimeError( f"Found more than one stateful callback of type `{type(callback).__name__}`. In the current" " configuration, this callback does not support being saved alongside other instances of the same type." f" Please consult the documentation of `{type(callback).__name__}` regarding valid settings for" " the callback state to be checkpointable." " HINT: The `callback.state_key` must be unique among all callbacks in the Trainer." ) seen_callbacks.add(callback.state_key)
null