I do not know the two ways of setting the device and what the local rank refers to. Can anybody explain this code to me?
if args.local_rank == -1:
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
else:
torch.distributed.init_process_group(backend='nccl')
torch.cuda.set_device(args.local_rank)
device = torch.device('cuda', args.local_rank)
Related
I'm running into a little bit of a snag and I can't seem to research my way out of this, so I'm hoping for some pointers.
I'm using an 3x MCP23017 chips and putting them to output so that I can control a few things. I'm using the Adafruit MCP23017 library on Github, and this works well with the following:
#!/usr/bin/env python
import time
import board
import busio
import RPi.GPIO as GPIO
from digitalio import Direction
from adafruit_mcp230xx.mcp23017 import MCP23017
GPIO.setmode(GPIO.BCM)
i2c = busio.I2C(board.SCL, board.SDA)
mcp1 = MCP23017(i2c, address=0x20)
mcp2 = MCP23017(i2c, address=0x24)
mcp3 = MCP23017(i2c, address=0x22)
#mcp1
one_port_pins = []
for pin in range(0, 15):
one_port_pins.append(mcp3.get_pin(pin))
for pin in one_port_pins:
pin.direction = Direction.OUTPUT
#mcp2
two_port_pins = []
for pin in range(0, 15):
two_port_pins.append(mcp2.get_pin(pin))
for pin in two_port_pins:
pin.direction = Direction.OUTPUT
#mcp3
three_port_pins = []
for pin in range(0, 15):
three_port_pins.append(mcp3.get_pin(pin))
for pin in three_port_pins:
pin.direction = Direction.OUTPUT
According to the example, I'm able to trigger them as such:
for pin in two_port_pins:
pin.value = True
time.sleep(0.2)
pin.value = False
time.sleep(0.2)
And this does trigger them and work great, however, at this stage, I would like to incorporate some of my other script, that would parse through some of the pin's need to be activated, although, I'm not quite sure how to match them.
Trying to print the lists one_port_pins, two_port_pins and three_port_pins gives me all sorts of data I'm not at all formiliar with when I try to print:
print(pin.__dict__)
>>> {'_pin': 0, '_mcp': <adafruit_mcp230xx.mcp23017.MCP23017 object at 0xb65d5230>}
>>> {'_pin': 1, '_mcp': <adafruit_mcp230xx.mcp23017.MCP23017 object at 0xb65d5230>}
>>> {'_pin': 2, '_mcp': <adafruit_mcp230xx.mcp23017.MCP23017 object at 0xb65d5230>}
Can someone tell me what I am looking at? How am I able to select a specific pin to activate?
Thank you!
I tried implementing Union-find algorithm for finding number of connected components in a graph.
Problem link - https://www.hackerearth.com/problem/algorithm/connected-components-in-a-graph/
Problem code in python -
def cc(n,edges):
length=len(edges)
l=[-1]*(n+1)
rank=[0]*(n+1)
for i in range(length):
a=edges[i][0]
b=edges[i][1]
union(a,b,rank,l)
count=0
for i in range(1,n+1):
if l[i]==-1:
count+=1
print(count)
def union(a,b,rank,l):
fromp=find(a,l)
top=find(b,l)
if rank[fromp]>rank[top]:
l[top]=fromp
elif rank[top]>rank[fromp]:
l[fromp]=top
else:
l[fromp]=top
rank[top]+=1
def find(a,l):
if l[a]==-1:
return a
par=find(l[a],l)
l[a]=par
return par
n,e=map(int,input().split())
edges=[]
for _ in range(e):
edges.append(list(map(int,input().split())))
cc(n,edges)
The code is not working and giving wrong answers and even runtime error for one test case.Could anyone please help?
this is my main code,but I don't know how to fix the problem?
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = torch.load('./checkpoints/fcn_model_5.pth') # 加载模型
model = model.to(device)
You are loading the checkpoint as a state dict, it is not a nn.module object.
checkpoint = './checkpoints/fcn_model_5.pth'
model = your_model() # a torch.nn.Module object
model.load_state_dict(torch.load(checkpoint ))
model = model.to(device)
The source of your problem is simply you are loading your model as a dict, instead of nn.Module. Here is an another approach you can employ without converting to nn.Module bloat adopted from here:
for k, v in model.items():
model[k] = v.to(device)
Now, you have an ordered dict with the items at correct place.
Please note that you will still have an ordered dict instead of nn.Module. You will not be able to forward pass anything from an ordered dict.
I am a beginner in Python programming. Using Python3 for class.
The code I have is:
#!/usr/binpython3
import arduino
def loop():
contin = True
while contin:
userinput = input()
if userinput == "quit":
contin = False
else:
contin = True
I am stuck at the "userinput = input()" portion of my code. For some reason, my program would not ask user for the input. How can I fix this?
Thank you!
Are you actually calling the function? That is, are you saying loop() at the end of your code?
I'm having difficulty with one small part of my code. I'm modifying a player's HP while they're in combat, but when exiting combat the HP resets to 100. This is odd because the enemy's HP is preserved. By using print(id(player.hp)) I can see that a new instance of player.hp is being created, I just don't know why. I've tried googling the issue but I can't find an example that fits my problem. I'll try to only include the pertinent parts of the code below (there's a lot of superfluous writing that isn't necessary here), but if I need to include everything I will.
class Alleyway(Scene):
room_items = []
room_characters = []
room_enemies = ["hobo"]
def __init__(self):
self.fresh_arrival = True
self.north = False
self.east = True
self.south = True
self.west = False
self.enemy = Hobo()
def fight(self, player, weapon): #Lots of what makes this fun is edited out
while True:
if self.enemy.hp > 0:
print("Do you attack or flee?")
words = input("> ").lower()
if words == "flee":
map_ = Map("alleyway")
game = Engine(map_)
game.play()
if words == "attack":
miss = randint(1,4)
if miss == 1:
print("Too bad, you miss!")
else:
print("You got him!")
self.enemy.hp -= weapon.damage
print("Hobo's HP: {}".format(max(self.enemy.hp, 0)))
if self.enemy.hp > 0:
print("The hobo takes a swing at you.")
hobomiss = randint(1,5)
if hobomiss == 1:
print("He missed!")
else:
print("Ouch, he got you!")
player.hp -= self.enemy.damage
print("Your HP: {}".format(max(player.hp, 0)))
else:
print("No idea what you mean. Attack the man or flee.")
else:
print("You defeat the hobo!")
print()
print("Dirty shoes and shank added to inventory.")
print()
shoes = DirtyShoes()
shank = Shank()
player.inventory.append(shoes)
player.inventory.append(shank)
self.room_enemies.remove("hobo")
map_ = Map("alleyway")
game = Engine(map_)
game.play()
When fight() is called, an instance of Player() is sent in as an argument, which has an instance variable of self.hp = 100.
This is still a work in progress so please gloss over the fact that it doesn't exit when the player dies and other silly things like that (:
Now, when the player flees in the middle of the fight, my goal is for the enemy's HP to be preserved, the player's HP to be preserved, and the items to be added to the player's inventory. So far, the enemy's HP is accurately preserved and everything else in my code regarding the enemy's HP and his alive/dead status work great when combat is exited. My issue is with player.hp -= enemy.damage, player.inventory.append(shoes), and player.inventory.append(shank). None of them work. The player.hp displays correctly during the fight and decreases as expected, however once the player exits combat the HP is reset to 100 and there is nothing added to the inventory. I've tried player.hp = player.hp - enemy.damage for the HP issue and it still creates a new variable. I'm just not sure what's going on since the enemy portions are working fine.
If more information is needed please let me know. And if there are any obvious ways my code can be improved I'm totally open to suggestions.
Got it! I was defining player = Player() inside of a method, so it only created the instance for that method (I think). So I defined it outside of the method and now the modified values stick!