hiascend commited on
Commit
7d4b235
·
verified ·
1 Parent(s): 6e29d7d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -35
app.py CHANGED
@@ -1,54 +1,42 @@
1
  import gradio as gr
2
- import spaces
3
  import torch
4
  import os
5
 
 
 
 
 
 
 
 
 
 
 
6
  torch.set_default_device('cuda')
7
 
 
8
 
9
- class LinearModel(torch.nn.Module):
10
- def __init__(self):
11
- super(LinearModel, self).__init__()
12
- self.linear = torch.nn.Linear(1, 1, device='cuda')
13
 
14
- def forward(self, x):
15
- out = self.linear(x)
16
- print('weight device: ' + str(self.linear.weight.device))
17
- return out
18
 
19
 
20
- def process(n: int):
21
- print(f'\n===process step {n}')
22
- print('cuda visible devices: ' + str(os.getenv('CUDA_VISIBLE_DEVICES')))
23
  print('cuda avaliable: ' + str(torch.cuda.is_available()))
24
- print('cuda device count: ' + str(torch.cuda.device_count()))
 
 
25
 
26
- model = LinearModel().cuda()
27
- x = torch.ones(1, device='cuda')
28
- y = model(x)
29
 
30
- print(model)
31
- print(x)
32
- print(y)
33
 
34
 
35
  @spaces.GPU
36
  def greet(n):
37
- process(2)
38
- return f"Hello {n} Tensor"
39
-
40
-
41
- def func(n):
42
- # step1, on cpu
43
- process(1)
44
-
45
- # step2, on gpu
46
- res = greet(n)
47
-
48
- # step3, on cpu
49
- process(3)
50
-
51
- return res
52
 
53
 
54
- gr.Interface(fn=func, inputs=gr.Number(), outputs=gr.Text()).launch()
 
1
  import gradio as gr
2
+ import spaces # 导入spaces时会应用torch补丁
3
  import torch
4
  import os
5
 
6
+ spaces.zero.torch.unpatch() # 手动调用解除torch补丁方法
7
+
8
+ os.environ['CUDA_VISIBLE_DEVICES'] = 'MIG-2f70e35e-577e-52c1-9054-bc9f9d04054e'
9
+
10
+ print('cuda visible devices: ' + str(os.getenv('CUDA_VISIBLE_DEVICES')))
11
+ print('cuda avaliable: ' + str(torch.cuda.is_available()))
12
+ print('cuda device count: ' + str(torch.cuda.device_count()))
13
+ print('cuda device name: ' + str(torch.cuda.get_device_name()))
14
+ print('cuda device capability: ' + str(torch.cuda.get_device_capability()))
15
+
16
  torch.set_default_device('cuda')
17
 
18
+ zero = torch.Tensor([0]).cuda()
19
 
20
+ one = torch.ones(2, 2, device='cuda')
 
 
 
21
 
22
+ two = torch.matmul(one, one).cuda()
 
 
 
23
 
24
 
25
+ def print_device():
 
 
26
  print('cuda avaliable: ' + str(torch.cuda.is_available()))
27
+ print('zero device: ' + str(zero.device))
28
+ print('one device: ' + str(one.device))
29
+ print('two device: ' + str(two.device))
30
 
 
 
 
31
 
32
+ print_device() # cpu
 
 
33
 
34
 
35
  @spaces.GPU
36
  def greet(n):
37
+ print('on zero gpu')
38
+ print_device() # cuda
39
+ return f"Hello {zero + n} Tensor"
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
 
42
+ gr.Interface(fn=greet, inputs=gr.Number(), outputs=gr.Text()).launch()