"git@developer.sourcefind.cn:change/sglang.git" did not exist on "d9b3b0188338c6a1411c2995db5e8da7f56f6e4d"
utils.py 1.55 KB
Newer Older
Jinjing Zhou's avatar
Jinjing Zhou committed
1
2

import socket
3
import os
4
import random
5
6
7
import scipy.sparse as spsp
import numpy as np
import dgl
Jinjing Zhou's avatar
Jinjing Zhou committed
8
9


10
11
12
def generate_ip_config(file_name, num_machines, num_servers):
    """Get local IP and available ports, writes to file."""
    # get available IP in localhost
Jinjing Zhou's avatar
Jinjing Zhou committed
13
14
15
16
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # doesn't even have to be reachable
        sock.connect(('10.255.255.255', 1))
17
        ip = sock.getsockname()[0]
Jinjing Zhou's avatar
Jinjing Zhou committed
18
    except ValueError:
19
        ip = '127.0.0.1'
Jinjing Zhou's avatar
Jinjing Zhou committed
20
21
    finally:
        sock.close()
22
23
24

    # scan available PORT
    ports = []
Jinjing Zhou's avatar
Jinjing Zhou committed
25
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
26
27
    start = random.randint(10000, 30000)
    for port in range(start, 65535):
28
29
30
31
32
33
34
        try:
            sock.connect((ip, port))
            ports = []
        except:
            ports.append(port)
            if len(ports) == num_machines * num_servers:
                break
Jinjing Zhou's avatar
Jinjing Zhou committed
35
    sock.close()
36
37
38
39
40
41
    if len(ports) < num_machines * num_servers:
        raise RuntimeError(
            "Failed to get available IP/PORT with required numbers.")
    with open(file_name, 'w') as f:
        for i in range(num_machines):
            f.write('{} {}\n'.format(ip, ports[i*num_servers]))  
42
43
44
45


def reset_envs():
    """Reset common environment variable which are set in tests. """
46
47
    for key in ['DGL_ROLE', 'DGL_NUM_SAMPLER', 'DGL_NUM_SERVER', \
                'DGL_DIST_MODE', 'DGL_NUM_CLIENT', 'DGL_DIST_MAX_TRY_TIMES']:
48
49
        if key in os.environ:
            os.environ.pop(key)
50
51
52
53


def create_random_graph(n):
    return dgl.rand_graph(n, int(n * n * 0.001))